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.

One strategie, two instruments
 Post subject: One strategie, two instruments Post rating: 0   New post Posted: Tue 28 Jan, 2014, 16:49 

User rating: 0
Joined: Tue 28 Jan, 2014, 16:45
Posts: 9
Location: Spain,
Hi all,

I'm new with JForex and I'm trying to create a strategie that opens or closes trades in two instruments at the same time.

It's that possible? Could you give me a simple sample.

Thanks.

Bernabe


 
 Post subject: Re: One strategie, two instruments Post rating: 0   New post Posted: Tue 28 Jan, 2014, 16:59 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
Bernabe wrote:
It's that possible? Could you give me a simple sample.
Yes it is, every common JForex-API routine in the wiki is supplied with an example strategy.
Bernabe wrote:
opens
See:
https://www.dukascopy.com/wiki/#Set_Market_Order (locate MarketOrder.java)
https://www.dukascopy.com/wiki/#Set_Conditional_Order (locate ConditionalOrder.java)
Bernabe wrote:
closes
See:
https://www.dukascopy.com/wiki/#Close_Orders
Bernabe wrote:
two instruments
Mind that you need to subscribe to those instruments, see:
https://www.dukascopy.com/wiki/#Subscribe_to_an_instrument
You can also let the user to select the instrument set from the strategy parameters, see:
https://www.dukascopy.com/wiki/#Strategy_parameters/Usage_of_all_types
If you wish to learn how to write JForex strategies, consider taking a look at our Strategy tutorial:
https://www.dukascopy.com/wiki/#Strategy_Tutorial


 
 Post subject: Re: One strategie, two instruments Post rating: 0   New post Posted: Wed 29 Jan, 2014, 12:53 

User rating: 0
Joined: Tue 28 Jan, 2014, 16:45
Posts: 9
Location: Spain,
Thanks for your answer.

I've tried with the code below. It is a modification of the SMASampleTrade.java code.
When I run it in backtest it does a lot of orders on EURUSD, almost on each new bar. On GBPUSD it looks ok.
Where am I going wrong?

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package onBarExample;

import com.dukascopy.api.*;
import java.util.HashSet;
import java.util.Set;


public class SMA2Ins implements IStrategy {
    private IEngine engine;
    private IConsole console;
    private IHistory history;
    private IContext context;
    private IIndicators indicators;
    private IUserInterface userInterface;   
    private IBar previousBar; 
    private IOrder order;
           
    private static final int PREV = 1;
    private static final int SECOND_TO_LAST = 0;
   
    @Configurable(value="Instrument value1")
    public Instrument myInstrument = Instrument.EURUSD;
    @Configurable(value="Instrument value2")
    public Instrument myInstrument2 = Instrument.GBPUSD;
    @Configurable(value="Offer Side value", obligatory=true)
    public OfferSide myOfferSide;
    @Configurable(value="Period value")
    public Period myPeriod = Period.TEN_MINS;
    @Configurable("SMA time period")
    public int smaTimePeriod = 30;
   
   
    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();
       
        //subscribe an instrument:
        Set<Instrument> instruments = new HashSet<Instrument>();
        instruments.add(myInstrument);             
        instruments.add(myInstrument2);                     
        context.setSubscribedInstruments(instruments, true);
    }

    public void onAccount(IAccount account) throws JFException {
    }

   
   
    /*
     * filter out from all IMessages the messages related with orders and
     * log them to the strategy's output tab
     */
    public void onMessage(IMessage message) throws JFException {       
        if(message.getOrder() != null)
            printMe("order: " + message.getOrder().getLabel() + " || message content: " + message.getContent());
    }

    public void onStop() throws JFException {
    }

    public void onTick(Instrument instrument, ITick tick) throws JFException {
    }
   
   
   
    /*
     * Implement our business logic here. Filter specific instrument and period.
     * Get the order and check whether the order with the same label exists in open state,
     * if yes then close it. Make a decision and submit a new order.
     */   
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {     
       
        if (!(instrument.equals(myInstrument) || instrument.equals(myInstrument2) && period.equals(myPeriod)))
        {
            return; //  quit
        }                 
             
        printMe("---->"+instrument.toString());
       
                         
        IEngine.OrderCommand myCommand = null;
        IEngine.OrderCommand myCommand2 = null;
        int candlesBefore = 2, candlesAfter = 0;
        //get SMA values of 2nd-to last and last (two last completed) bars
        previousBar = myOfferSide == OfferSide.ASK ? askBar : bidBar;
        long currBarTime = previousBar.getTime();
        double sma[] = indicators.sma(instrument, period, myOfferSide, IIndicators.AppliedPrice.CLOSE,
                smaTimePeriod, Filter.NO_FILTER, candlesBefore, currBarTime, candlesAfter);

         /*print some message so we can later compare the results with a chart,
         *If SMA is up-trend (green line in sample picture) execute BUY order.
         *If SMA is down-trend (red line in sample picture) execute SELL order.
         */
        printMe(String.format("Bar SMA Values: Second-to-last = %.5f; Last Completed = %.5f", sma[SECOND_TO_LAST], sma[PREV]));       
        if(sma[PREV] > sma[SECOND_TO_LAST]){
            printMe("SMA in up-trend"); //indicator goes up
              if (instrument.equals(Instrument.EURUSD)) myCommand = IEngine.OrderCommand.BUY;
              if (instrument.equals(Instrument.GBPUSD)) myCommand2 = IEngine.OrderCommand.BUY;
        } else if(sma[PREV] < sma[SECOND_TO_LAST]){
            printMe("SMA in down-trend"); //indicator goes down
              if (instrument.equals(Instrument.EURUSD)) myCommand = IEngine.OrderCommand.SELL;
              if (instrument.equals(Instrument.GBPUSD)) myCommand2 = IEngine.OrderCommand.SELL;
         } else {
            return;
        }
       
        /*check if the order already exists. If exists, then check if the processing order's command is the same as myCommand.
         * If it is the same, then do nothing (let the order stay in open state and continues to processing).
         * If the order command is different (SMA trend changes direction) from the current order's command,
         * then close the opened order and create new one:
         */
         
        String MyOrderID = "OrderID";
        if (instrument.equals(Instrument.EURUSD))
        {
            MyOrderID = "OrdenEURUSD";
            order = engine.getOrder(MyOrderID);                       
            if(order != null && engine.getOrders().contains(order) && order.getOrderCommand() != myCommand){
                order.close();
                order.waitForUpdate(IOrder.State.CLOSED); //wait till the order is closed
                console.getOut().println("Order " + order.getLabel() + " is closed");           
            }
            //if the order is new or there is no order with the same label, then create a new order:
            if(order == null || !engine.getOrders().contains(order)){
                engine.submitOrder(MyOrderID, instrument, myCommand, 0.1);           
            }
        }
        if (instrument.equals(Instrument.GBPUSD))
        {
            MyOrderID = "OrdenGBPUSD";
            order = engine.getOrder(MyOrderID);                       
            if(order != null && engine.getOrders().contains(order) && order.getOrderCommand() != myCommand2){
                order.close();
                order.waitForUpdate(IOrder.State.CLOSED); //wait till the order is closed
                console.getOut().println("Order " + order.getLabel() + " is closed");           
            }
            //if the order is new or there is no order with the same label, then create a new order:
            if(order == null || !engine.getOrders().contains(order)){
                engine.submitOrder(MyOrderID, instrument, myCommand2, 0.1);           
            }     
       }
                             
    }
   
    private void printMe(String toPrint){
        console.getOut().println(toPrint);
    }
}


 
 Post subject: Re: One strategie, two instruments Post rating: 0   New post Posted: Wed 29 Jan, 2014, 14:16 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
Update the bar logging to the following:
        printMe("---->" + instrument + " " + period);

And now check your own logs - you are not working with the bars you think you are working with - thus the flaw is in the bar filtering condition:
        if (!(instrument.equals(myInstrument) || instrument.equals(myInstrument2) && period.equals(myPeriod))) {
            return; // quit
        }


 
 Post subject: Re: One strategie, two instruments Post rating: 0   New post Posted: Fri 31 Jan, 2014, 13:48 

User rating: 0
Joined: Tue 28 Jan, 2014, 16:45
Posts: 9
Location: Spain,
I have modified the code like this:

        if ( instrument.equals(myInstrument) || instrument.equals(myInstrument2) && period.equals(myPeriod) ) 
{


Below is the rest of my onBar() method.

And I get messages like this:

11:44:21 SMA in up-trend
11:44:21 Bar SMA Values: Second-to-last = 1.35338; Last Completed = 1.35340
11:44:21 ---->EUR/USD 10 Secs
11:44:20 SMA in up-trend
11:44:20 Bar SMA Values: Second-to-last = 1.35336; Last Completed = 1.35338
11:44:20 ---->EUR/USD 10 Secs
11:44:20 SMA in up-trend
11:44:20 Bar SMA Values: Second-to-last = 1.35334; Last Completed = 1.35336
11:44:20 ---->EUR/USD 10 Secs
11:44:20 SMA in up-trend
11:44:20 Bar SMA Values: Second-to-last = 1.35332; Last Completed = 1.35334
11:44:20 ---->EUR/USD 10 Secs


I can't unsderstand why I'm still having all kind of periods passing this filter. What is wrong with my code?

Regards
Bernabe


 
 Post subject: Re: One strategie, two instruments Post rating: 0   New post Posted: Fri 31 Jan, 2014, 14:07 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
Bernabe wrote:
What is wrong with my code?
You are still on the same line. You should use parentheses in order to avoid the ambiguity of the code. To learn more about conditional operators see:
https://docs.oracle.com/javase/tutorial/ ... s/op2.html


 
 Post subject: Re: One strategie, two instruments Post rating: 0   New post Posted: Fri 31 Jan, 2014, 16:12 

User rating: 0
Joined: Tue 28 Jan, 2014, 16:45
Posts: 9
Location: Spain,
Ok, I found out.

Thanks for your help.


 

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