Dukascopy
 
 
Wiki JStore Search Login

Trailing step not moving - (works on backtest, not on demo trading)
 Post subject: Trailing step not moving - (works on backtest, not on demo trading) Post rating: 1   New post Posted: Sun 26 May, 2013, 01:33 
User avatar

User rating: 1
Joined: Mon 04 Mar, 2013, 10:46
Posts: 15
Location: Australia, Leichhardt
I have been testing a strategy of mine and it sets a stop loss and trailing step after waiting for the order to be filled.

It works perfectly on backtesting, but the trailing step doesnt move at all as Ive tested on 4 different trades on a couple of different currency pairs when run on a demo account on live data this week (thursday and friday 23rd may), the SL and TS is definately set as can be seen in the 2 attached pics.

Attached 2 screen shots of it on this example trade showing the stop loss still sitting back at 17 pips where it was initially set, and the price has gone in my favour more than 30 pips (the the SL should have moved 3 times since the trailing step is set to 10 pips) the messages in the other photo show the actual trade messages and amounts, which all looked right to me. And like I said the trailing step works on a backtest, just not running on a demo account for some reason.

Any help or ideas...


the trade opening parts of the code are:
public Instrument subInstrument = Instrument.USDCHF ;
    public void onStart(IContext context) throws JFException {    /**  ON START  **  ON START  **  ON START  **  ON START  **  ON START  **/
        { Set<Instrument> subscribedInstruments = new HashSet<Instrument>();
         subscribedInstruments.add(subInstrument);
         context.setSubscribedInstruments(subscribedInstruments);
        }

    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException  /** ONBAR */
    {  if(period == selectedperiod && subInstrument == instrument && pipSet == true)
      {  if (positionsTotal(subInstrument) == 0 )         /** LOOKING FOR A SETUP TO TRADE **/
         {  if (prevC[0] <  highestInArray(0,6,prevMAAve) - (17*pip) && blockSell == false)
             {  sell(subInstrument, engine, 17, 0.001);
                marketorder[0].waitForUpdate(5000, IOrder.State.FILLED);
                 marketorder[0].setStopLossPrice(bidPrice + (17*pip), OfferSide.BID, 10); //trailing step set
             }
 
           if (prevC[0] >  lowestInArray(0,6,prevMAAve) + (17*pip) && blockBuy == false )
             {  buy(subInstrument, engine, 17, 0.001);
                marketorder[0].waitForUpdate(5000, IOrder.State.FILLED);
                 marketorder[0].setStopLossPrice(bidPrice - (17*pip), OfferSide.BID, 10); //trailing step set
             }             
        }
  }
    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();
         long time = new java.util.Date().getTime();
         label = label.substring(0, 2) + label.substring(3, 5);
         label = label + time;
         label = label.toLowerCase();
         return label;
     }

// BUY AND SELL Calls below lastAsk
      public void sell(Instrument instrument, IEngine engine, int endLossPipLevel, double volumeParam)  throws JFException //slip below
       {  marketorder[0] = engine.submitOrder(getLabel(instrument) , instrument, IEngine.OrderCommand.SELL, volumeParam, 0, 20, bidPrice
                        + pip *endLossPipLevel, 0);         
       }
      public void buy(Instrument instrument, IEngine engine, int endLossPipLevel, double volumeParam)  throws JFException
       {  marketorder[0] =  engine.submitOrder(getLabel(instrument) , instrument, IEngine.OrderCommand.BUY, volumeParam, 0, 20, askPrice
                        - pip * endLossPipLevel, 0);
       }


Image
Image


Attachments:
USDCHF trailing SL not moving B.jpg [466.21 KiB]
Downloaded 968 times
USDCHF trailing SL not moving A.jpg [637.23 KiB]
Downloaded 987 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: Trailing step not moving - (works on backtest, not on demo trading) Post rating: 0   New post Posted: Mon 27 May, 2013, 09:49 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
The trailing step does work both with live data and in historical tester, you can make sure of this by using the following example strategy (it uses the EUR/NOK instrument on purpose for making fast 10-pip moves):
https://www.dukascopy.com/wiki/#Set_Stop_Loss_price/Trailing_step_tracking
For your particular case, to make sure that the stop loss non-move is not due to allegedly wrong trailing step execution, consider adding similar trailing step verification as it is done in the given example (see the onTick method there).


 
 Post subject: Re: Trailing step not moving - (works on backtest, not on demo trading) Post rating: 0   New post Posted: Mon 27 May, 2013, 13:55 
User avatar

User rating: 1
Joined: Mon 04 Mar, 2013, 10:46
Posts: 15
Location: Australia, Leichhardt
Thanks support, I'll try that.


 
 Post subject: Re: Trailing step not moving - (works on backtest, not on demo trading) Post rating: 0   New post Posted: Wed 29 May, 2013, 02:23 
User avatar

User rating: 1
Joined: Mon 04 Mar, 2013, 10:46
Posts: 15
Location: Australia, Leichhardt
API Support wrote:
Just a note, the example has an error in it.

This is on the above examples page inside sample TrailingStepTest.java :
BUY setup sl and ts: [this one below is good]
IOrder order = engine.submitOrder("buyWithTrailing_"+tick.getTime(), instrument, OrderCommand.BUY, 0.001);
        order.waitForUpdate(2000, IOrder.State.FILLED);     
        slMoves.put(order, 0);
        order.setStopLossPrice(tick.getBid() - instrument.getPipValue() * 10, OfferSide.BID, trailingStep);
SELL setup sl and ts: [this one below is no good]
order = engine.submitOrder("sellWithTrailing_"+tick.getTime(), instrument, OrderCommand.SELL, 0.001);
        order.waitForUpdate(2000, IOrder.State.FILLED);
        slMoves.put(order, 0);
        order.setStopLossPrice(tick.getAsk() - instrument.getPipValue() * 10, OfferSide.BID, trailingStep);
The SELL setStopLossPrice( ) line should be plus "+" 10 pips not minus 10 pips. (opposite of the BUY)

Just testing my code further to find my SL issue. I'll report back soon.


 
 Post subject: Re: Trailing step not moving - (works on backtest, not on demo trading) Post rating: 0   New post Posted: Wed 29 May, 2013, 08:00 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
The example has been fixed.


 
 Post subject: Re: Trailing step not moving - (works on backtest, not on demo trading) Post rating: 0   New post Posted: Wed 29 May, 2013, 15:51 
User avatar

User rating: 1
Joined: Mon 04 Mar, 2013, 10:46
Posts: 15
Location: Australia, Leichhardt
So Ive done some testing and simplified my strategy down so it will show the problem fairly quickly on USDMXN.

Maybe Im doing something wrong but I cant see where, Im using this page as reference for how to open the trades using the third submitOrder options from the jforex javadoc.


Using the IOrder submitOrder(String label,
Instrument instrument,
IEngine.OrderCommand orderCommand,
double amount,
double price,
double slippage,
double stopLossPrice,
double takeProfitPrice)
throws JFException

then after upto 2sec wait it sets the stop loss and trailing stop

Ive attached the sample java file to reproduce the problem, if you use the V2 part of the code instead of the V1 it works 100%, but I dont want to rely on the stop loss getting set later, I want to set it right when the order gets placed, so this is not a fix just a lower quality work around, the only difference in the V1 and V2 is the stoplossprice and takeprofitprice are not implemented while opening the order in V2.
package jforex.orders.sl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import com.dukascopy.api.IEngine.OrderCommand;
import com.dukascopy.api.IMessage.Reason;
import com.dukascopy.api.*;
import java.util.*;
import com.dukascopy.api.IIndicators.MaType;
import com.dukascopy.api.IIndicators;
import java.awt.Color;
import java.lang.Object;
import java.awt.Font;
import static java.lang.Math.*;
import java.text.DecimalFormat;
import com.dukascopy.api.IIndicators.MaType;
import com.dukascopy.api.IIndicators;

public class StrategySLTS implements IStrategy {
    private IContext context = null;
    private IEngine engine = null;
    private IHistory history = null;
    private IIndicators indicators = null;
    private IConsole console = null;
    @Configurable ("Period")
     public  Period selectedperiod = Period.TEN_SECS; // <----- 15mins
    private Filter indFilter = Filter.WEEKENDS;
    private IUserInterface userInterface;   

    private IOrder marketorder1 = null;
    private IOrder marketorder2 = null;
   
    private double bidPrice = 0;
    private double askPrice = 0;
    private long barTime = 0;
    IBar lastBid =  null;
    IBar lastAsk =  null;
    private  Instrument subInstrument = Instrument.USDMXN ;
   
   
   
   
   
     
    public void onStart(IContext context) throws JFException {
        this.context = context; 
        this.engine = context.getEngine();
        this.indicators = context.getIndicators();
        this.history = context.getHistory();
        this.console = context.getConsole();
        this.userInterface = context.getUserInterface();
        Set<Instrument> subscribedInstruments = new HashSet<Instrument>();
         subscribedInstruments.add(subInstrument);
         context.setSubscribedInstruments(subscribedInstruments);
       }
// BUY AND SELL V1   Problem with trailing stop
      private void sell(Instrument instrument, IEngine engine, double amount)  throws JFException //slip below
       {  marketorder1 = engine.submitOrder("sellc" +barTime , instrument, IEngine.OrderCommand.SELL, amount, 0, 20, bidPrice + 0.0075, 0);         
       }
      private void buy(Instrument instrument, IEngine engine, double amount)  throws JFException
       {  marketorder2 =  engine.submitOrder("buyc" + barTime , instrument, IEngine.OrderCommand.BUY, amount, 0, 20, askPrice - 0.0075, 0);
       }
// BUY AND SELL V2   Working trailing stop
//      private void sell(Instrument instrument, IEngine engine, double amount)  throws JFException //slip below
//       {  marketorder1 = engine.submitOrder("sellc" +barTime , instrument, IEngine.OrderCommand.SELL, amount, 0, 20, bidPrice + 0.0075, 0);         
//       }
//      private void buy(Instrument instrument, IEngine engine, double amount)  throws JFException
//       {  marketorder2 =  engine.submitOrder("buyc" + barTime , instrument, IEngine.OrderCommand.BUY, amount, 0, 20, askPrice - 0.0075, 0);
//       }

    public void onAccount(IAccount account) throws JFException {
    }

    public void onMessage(IMessage message) throws JFException {
    }

    public void onStop() throws JFException {
    }

    public void onTick(Instrument instrument, ITick tick) throws JFException {
    }
   
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException
    {  if(period == selectedperiod && subInstrument == instrument)
         {  IBar nowBar = history.getBar(subInstrument, Period.TEN_SECS, OfferSide.BID, 0);
            IBar nowBarAsk = history.getBar(subInstrument, Period.TEN_SECS, OfferSide.ASK, 0);
            barTime = nowBar.getTime();
            bidPrice = nowBar.getClose();
            askPrice = nowBarAsk.getClose();
 
            if (positionsTotal(subInstrument) == 0 )         /** LOOKING FOR A SETUP TO TRADE **/
              {  sell(subInstrument, engine, 0.10);
                 marketorder1.waitForUpdate(2000, IOrder.State.FILLED);
                 marketorder1.setStopLossPrice(bidPrice + 0.0070, OfferSide.BID, 10);
                     
                 buy(subInstrument, engine, 0.10);
                 marketorder2.waitForUpdate(2000, IOrder.State.FILLED);
                 marketorder2.setStopLossPrice(bidPrice - 0.0070, OfferSide.BID, 10);
     

              }
       
         }
    }
   
   
    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;
    }   
}


 
 Post subject: Re: Trailing step not moving - (works on backtest, not on demo trading) Post rating: 0   New post Posted: Wed 29 May, 2013, 16:57 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
The issue has been registered. As a workaround consider submitting orders without the stop loss parameter (i.e. use 0 for SL parameter when calling IEngine.submitOrder) and the trailing step will work as expected.


 
 Post subject: Re: Trailing step not moving - (works on backtest, not on demo trading) Post rating: 1   New post Posted: Thu 30 May, 2013, 12:17 
User avatar

User rating: 164
Joined: Mon 08 Oct, 2012, 10:35
Posts: 676
Location: NetherlandsNetherlands
Hi,

This is another workaround:
- submit orders without SL
- implement in onMessage() an initial SL:
public void onMessage(IMessage message) throws JFException
{
    IOrder anOrder;
    double slPrice;

    switch (message.getType())
    {
        case ORDER_FILL_OK:
            anOrder = message.getOrder();
            if (Double.compare(anOrder.getStopLossPrice(),0) == 0) // there is no SL yet
            {
                slPrice = 10; // or calculate SL the way you want
                anOrder.setStopLossPrice(slPrice);
                anOrder.waitForUpdate(2000);
            }
            break;
    }
}

- implement in onTick() the trailing SL:
public void onTick(Instrument instrument, ITick tick) throws JFException
{
    double newSL;

    for (IOrder order : engine.getOrders())
    {
        if (conditions_ok) // <-- you have to implement your trailing SL conditions here
        {
            order.setStopLossPrice(newSl);
            order.waitForUpdate(2000);
        }
    }
}


 
 Post subject: Re: Trailing step not moving - (works on backtest, not on demo trading) Post rating: 0   New post Posted: Sun 16 Jun, 2013, 02:31 
User avatar

User rating: 1
Joined: Mon 04 Mar, 2013, 10:46
Posts: 15
Location: Australia, Leichhardt
thanks tcsabina,

applying on message at least works around the scenario where the order filling takes more than 5 seconds, which could happen and could result in NO stop loss set.
The scenario that isnt covered is if the strategy or pc or server unexpectedly stops running between the time of trade submitting and the stop loss being set, obviosly no stop loss will be set either which is why it is important to have the option to set the SL in the SAME command as the order creation like I was trying to do.

So any update on this one? a fix scheduled.


 
 Post subject: Re: Trailing step not moving - (works on backtest, not on demo trading) Post rating: 0   New post Posted: Tue 18 Jun, 2013, 18:40 
User avatar

User rating: 70
Joined: Sat 22 Sep, 2012, 17:43
Posts: 118
Location: Brazil, Fortaleza, Ceará
You have a trailing stop problem so finding different ways to submitOrder plus the initial STOP won't help you.
I've taken a look at the screenshots you provided which indicated Trailing stop activity for your earlier buy (Order #199711692 / Position #51451045)
but not for your subsequent sell. You didn't mention any successful buy-side trail but i've taken this idea from the console output in the screenshot
and so took a look here:
1  public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException  /** ONBAR */
2  {  if(period == selectedperiod && subInstrument == instrument && pipSet == true)
3     {  if (positionsTotal(subInstrument) == 0 )         /** LOOKING FOR A SETUP TO TRADE **/
4         {  if (prevC[0] <  highestInArray(0,6,prevMAAve) - (17*pip) && blockSell == false)                         <---- SELL SIDE LOGIC
5             {  sell(subInstrument, engine, 17, 0.001);
6                marketorder[0].waitForUpdate(5000, IOrder.State.FILLED);
7                 marketorder[0].setStopLossPrice(bidPrice + (17*pip), OfferSide.BID, 10); //trailing step set
8             }
9   
10           if (prevC[0] >  lowestInArray(0,6,prevMAAve) + (17*pip) && blockBuy == false )                         <---- BUY SIDE LOGIC
11            {  buy(subInstrument, engine, 17, 0.001);
12               marketorder[0].waitForUpdate(5000, IOrder.State.FILLED);
13                marketorder[0].setStopLossPrice(bidPrice - (17*pip), OfferSide.BID, 10); //trailing step set
14            }             
15       }
  }
I didn't like the look of Line 7 and so would ask that you begin the problem solving by rewriting it as:

marketorder[0].setStopLossPrice(askPrice + (17*pip), OfferSide.ASK, 10); //trailing step set

Report back and we'll see what else might be going on.

Note:
No where could I see how you defined 'pip' - I can only presume it's set to Instrument.pipValue().
Also, V1 and V2 above are identical.
0.0075 constants will play nice until you test currencies with different decimal bases.


 
 Post subject: Re: Trailing step not moving - (works on backtest, not on demo trading) Post rating: 0   New post Posted: Mon 01 Jul, 2013, 13:25 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
Fixed with JForex-API 2.7.11.


 
 Post subject: Re: Trailing step not moving - (works on backtest, not on demo trading) Post rating: 0   New post Posted: Sun 07 Jul, 2013, 14:47 
User avatar

User rating: 1
Joined: Mon 04 Mar, 2013, 10:46
Posts: 15
Location: Australia, Leichhardt
Thanks for looking at the problem too Critical.

In answer to the questions:
CriticalSection wrote:
I've taken a look at the screenshots you provided which indicated Trailing stop activity for your earlier buy (Order #199711692 / Position #51451045)

That was a manual trade and it had no problems with trailing step, sorry yes it was a confusing trade log because of that.
As for the 2 questions about pip value, 'pip' in my first code example is set by first making global variables: public double pip = 0.0; public boolean pipSet = false;
then in the onTick:
public void onTick(Instrument instrument, ITick tick) throws JFException 
    { if (instrument == subInstrument)
       {  if (pipSet == false)
            {  pip = subInstrument.getPipValue();
               if ( pip > 0.0000000 )
                   {  pipSet = true; }
            }
        }
    }

CriticalSection wrote:
I didn't like the look of Line 7 and so...

I know its quite common to use the ask side price there, but I specifically wanted the bid price to set the stop loss against in this strategy, and I know if the spread changes it can wreak havoc with especially a small stop loss .
And yes youre right about the example code where theres a V1 and V2, my typo: V2 was meant to have a 0 zero stop loss, which I found made the whole thing function as expected just not as desired.
CriticalSection wrote:
0.0075 constants will play nice until you test currencies with different decimal bases.

I know this. This was in the last code example which was a massively simplified example of my strategy just to simplify debuging for me and the dukascopy staff, yet still make the bug show its head.

So again further if I can refer to your example of using the ask price rather than bid price to create my stop loss setting, this may even work (I didnt test it), but its not what I want this strategy to do so its not even a workaround in this case.

Hmmm, Wondering when API 2.7.11 will be implemented on live, it looks like even the demo server is not on this API and live is even further behind.


 

Jump to:  

  © 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