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.

How to disable log4j outputs from SDK JForex
 Post subject: How to disable log4j outputs from SDK JForex Post rating: 0   New post Posted: Tue 25 Jun, 2019, 11:18 

User rating: 2
Joined: Fri 06 Apr, 2018, 17:06
Posts: 23
Location: Poland,
Hi.
I started tests SDK on my VPS. I downloaded this file (https://www.dukascopy.com/client/jforex ... -3-SDK.zip) and read how to use SDK in Eclipse from there (https://www.dukascopy.com/wiki/en/devel ... in-eclipse). Then I running example from singlejartest package (Main.java), everything works fine, strategy is running. I can open jforex which I have installed on the disk and watch how this strategy works on the market. I can run strategy without jforex gui, only from console as java -jar demostrategy.jar, this is great :o :P I'm impressed. btw. Great job jforex team. But........ I don't know how to resolve problem with log4j outputs from SDK JForex version running on my VPS. I don't want these messages, becouse I want to start simple strategy without GUI (swing elements like JFrame etc), only console version. I use Linux CentOs 7. I exported all project from Eclipse to jar format, and sended to my VPS, and run with command (java -jar myproject.jar] ..... And process in java is started. So, then I use key to stop this process CTRL + Z and put next command "bg", thease means I want to run this process in background all time. Then I want to close terminal, like Putty or Ubuntu terminal with ssh client, but these logs from LOGGER display information about opened order, closed order, debug and other things. I found this, but for me not works:
1. https://www.dukascopy.com/fxcomm/q_a/?a ... &q_id=1469
2. https://www.dukascopy.com/swiss/english ... g4j#p85099
3. https://www.dukascopy.com/swiss/english ... g4j#p88643

I don't have graphic mode (Gnome) on my VPS (Linux CentOS 7), so is only one way - to use the console, but how to disable these all messages from server? How to disable these all information for current API ?

Ok, when I logout and login again to VPS I don't see these messages, so strategy in process working in background silent, do not see spam in my console and strategy still running, but I want to know how to turn off these messages or something more about this...

Regards.


 
 Post subject: Re: How to disable log4j outputs from SDK JForex Post rating: 0   New post Posted: Tue 25 Jun, 2019, 15:41 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
Hello,

Add this code to the your program entry point method.
        org.apache.log4j.Logger.getRootLogger().removeAllAppenders();
        org.apache.log4j.Logger.getRootLogger().addAppender(new NullAppender());


 
 Post subject: Re: How to disable log4j outputs from SDK JForex Post rating: 0   New post Posted: Tue 25 Jun, 2019, 23:47 

User rating: 2
Joined: Fri 06 Apr, 2018, 17:06
Posts: 23
Location: Poland,
Hello API Support.

Ok, i put this code at the top of main function. I use example name MA_Play from singlejartest package like I said. But i made little modifications, this is my Main.java and MA_Play.java files code. And.. I run this with yours solution like you see in the picture. Messages about log client to server etc is disabled, but still I need to know how to block these messages about orders.

Main.java
/**
 * Copyright (c) 2018 Dukascopy (Suisse) SA. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution 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.
 *
 * Neither the name of Dukascopy (Suisse) SA or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. DUKASCOPY (SUISSE) SA ("DUKASCOPY")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL DUKASCOPY OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF DUKASCOPY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 */
package singlejartest;

import com.dukascopy.api.Instrument;
import com.dukascopy.api.system.ClientFactory;
import com.dukascopy.api.system.IClient;
import com.dukascopy.api.system.ISystemListener;

import org.apache.log4j.varia.NullAppender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.Set;

import javax.swing.JFrame;
import java.awt.Dimension;

/**
 * This small program demonstrates how to initialize Dukascopy client and start a strategy
 */
public class Main {
    private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);

    private static String jnlpUrl = "https://platform.dukascopy.com/demo/jforex.jnlp";
    private static String userName = "DEMO2bwYFU";
    private static String password = "bwYFU";

    private static IClient client;
   
    private static int lightReconnects = 3;

    public static void main(String[] args) throws Exception {
       
       org.apache.log4j.Logger.getRootLogger().removeAllAppenders();
        org.apache.log4j.Logger.getRootLogger().addAppender(new NullAppender());
       
       
       
       
       // main setup app
       
       //JFrame frame = new JFrame("test simple strategy with SDK Jforex 3");
       //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       //frame.setPreferredSize(new Dimension(400,400));
       //frame.setVisible(true);
       //frame.pack();
       
        //get the instance of the IClient interface
        client = ClientFactory.getDefaultInstance();

        setSystemListener();
        LOGGER.info("Connecting...");
        tryToConnect();
        if (!client.isConnected()) {
            LOGGER.error("Failed to connect Dukascopy servers");
            System.exit(1);
        }
        subscribeToInstruments();

        LOGGER.info("Starting strategy");
        client.startStrategy(new MA_Play());
       
        //now it's running
       
       
    }

    private static void setSystemListener() {
        //set the listener that will receive system events
        client.setSystemListener(new ISystemListener() {

            @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() {
                tryToReconnect();
            }
        });
    }

    private static void tryToConnect() throws Exception {
        //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--;
        }
    }

    private static void tryToReconnect() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                while(!client.isConnected()) {
                    try {
                        if (lightReconnects > 0 && client.isReconnectAllowed()) {
                            client.reconnect();
                            --lightReconnects;
                        } else {
                            tryToConnect();
                        }
                        if(client.isConnected()) {
                            break;
                        }
                    } catch (Exception e) {
                        LOGGER.error(e.getMessage(), e);
                    }
                    sleep(60 * 1000);
                }
            }

            private void sleep(long millis) {
                try {
                    Thread.sleep(millis);
                } catch (InterruptedException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        };
        new Thread(runnable).start();
    }

    private static void subscribeToInstruments() {
        Set<Instrument> instruments = new HashSet<>();
        instruments.add(Instrument.EURUSD);
        LOGGER.info("Subscribing instruments...");
        client.setSubscribedInstruments(instruments);
    }
}

MA_Play.java
/**
 * Copyright (c) 2017 Dukascopy (Suisse) SA. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution 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.
 *
 * Neither the name of Dukascopy (Suisse) SA or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. DUKASCOPY (SUISSE) SA ("DUKASCOPY")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL DUKASCOPY OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF DUKASCOPY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 */
package singlejartest;

import com.dukascopy.api.*;

public class MA_Play implements IStrategy {
    private IEngine engine = null;
    private IIndicators indicators = null;
    private int tagCounter = 0;
    private double[] ma1 = new double[Instrument.values().length];
    private IConsole console;

    public void onStart(IContext context) throws JFException {
        engine = context.getEngine();
        indicators = context.getIndicators();
        this.console = context.getConsole();
        //console.getOut().println("Started");
    }

    public void onStop() throws JFException {
        for (IOrder order : engine.getOrders()) {
            order.close();
        }
        //console.getOut().println("Stopped");
    }

    public void onTick(Instrument instrument, ITick tick) throws JFException {
       
       Double random = Math.random() * 100;
        sendOrder(instrument, tick, random.intValue());
       
       /*
        if (ma1[instrument.ordinal()] == -1) {
            ma1[instrument.ordinal()] = indicators.ema(instrument, Period.TEN_SECS, OfferSide.BID, IIndicators.AppliedPrice.MEDIAN_PRICE, 14, 1);
        }
        double ma0 = indicators.ema(instrument, Period.TEN_SECS, OfferSide.BID, IIndicators.AppliedPrice.MEDIAN_PRICE, 14, 0);
        if (ma0 == 0 || ma1[instrument.ordinal()] == 0) {
            ma1[instrument.ordinal()] = ma0;
            return;
        }

        double diff = (ma1[instrument.ordinal()] - ma0) / (instrument.getPipValue());

        if (positionsTotal(instrument) == 0) {
            if (diff > 1) {
                engine.submitOrder(getLabel(instrument), instrument, IEngine.OrderCommand.SELL, 0.001, 0, 0, tick.getAsk()
                        + instrument.getPipValue() * 10, tick.getAsk() - instrument.getPipValue() * 15);
            }
            if (diff < -1) {
                engine.submitOrder(getLabel(instrument), instrument, IEngine.OrderCommand.BUY, 0.001, 0, 0, tick.getBid()
                        - instrument.getPipValue() * 10, tick.getBid() + instrument.getPipValue() * 15);
            }
        }
        ma1[instrument.ordinal()] = ma0;
        */
    }
   
    public void sendOrder(Instrument instrument, ITick tick, int random) throws JFException {
        if (engine.getOrders(instrument).size() > 0) return;   
        //console.getOut().println(random);   
        if (random > 50) {
            engine.submitOrder(getLabel(instrument), instrument, IEngine.OrderCommand.BUY, 0.001, 0, 0, tick.getBid()
                        - instrument.getPipValue() * 1, tick.getAsk() + instrument.getPipValue() * 1);
        } else {
            engine.submitOrder(getLabel(instrument), instrument, IEngine.OrderCommand.SELL, 0.001, 0, 0, tick.getAsk()
                        + instrument.getPipValue() * 1, tick.getAsk() - instrument.getPipValue() * 1);
        }     
    }

    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) {
    }

    //count open positions
    protected int positionsTotal(Instrument instrument) throws JFException {
        int counter = 0;
        for (IOrder order : engine.getOrders(instrument)) {
            if (order.getState() == IOrder.State.FILLED) {
                counter++;
            }
        }
        return counter;
    }

    protected String getLabel(Instrument instrument) {
        String label = instrument.name();
        label = label.substring(0, 2) + label.substring(3, 5);
        label = label + (tagCounter++);
        label = label.toLowerCase();
        return label;
    }

    public void onMessage(IMessage message) throws JFException {
    }

    public void onAccount(IAccount account) throws JFException {
    }
}


Image


Attachments:
26062019_SDK_test_errors.png [202.06 KiB]
Downloaded 246 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: How to disable log4j outputs from SDK JForex Post rating: 0   New post Posted: Thu 27 Jun, 2019, 00:11 

User rating: 2
Joined: Fri 06 Apr, 2018, 17:06
Posts: 23
Location: Poland,
Ok. Probably I was looking in the wrong place. I did not know commands like "tail" or "tee" until now. I used this command and it works. No logs in console after start strategy, because they are written to output.text file. And then CTRL + Z, and BG, and process works in background and save to this file...
java -jar JDK_simpledemostrategy.jar > output.txt 2>&1 &

https://www.devdungeon.com/content/standard-input-output-and-error-java

Ok, Problem solved :twisted:
----------------
btw. This is very interesting, heh. When this strategy from example in the previous post running on VPS, and I watch in JForex desktop version on my computer, how this strategy open order by 1 pips up/down with SL and TP. But I don't wait to this moment when price hit tp or sl, only I'd close order manualy, and this program interprets that there is no position again and opens another one. What I want to say... This strategy running on another computer than my, as protector for me or something like that. Heh, I learned something new right now :lol: :P
Thanks.


 

Jump to:  

cron
  © 1998-2024 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