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.

Equity Change Strategy
 Post subject: Equity Change Strategy Post rating: 0   New post Posted: Tue 01 Oct, 2013, 01:36 

User rating: 3
Joined: Sat 04 May, 2013, 03:34
Posts: 33
Location: CanadaCanada
I am trying to write a strategy that looks at the value of the equity and then closes all positions when when it reaches a value + or - as a % of the starting equity. For some reason the if statement that calculates if the current equity is greater or less than the TP or SL + and - values is not working. I may have the syntax incorrect. I am not sure
package jforex.strategies;

import com.dukascopy.api.*;
import java.text.DecimalFormat;

public class TakeTotalProfitEquity implements IStrategy {

    private IEngine engine;
    private IConsole console;
    private IHistory history;
    private IContext context;
    private IIndicators indicators;
    private IUserInterface userInterface;
   
    @Configurable("Total take profit (% of account)")
    public double tpPercent = 1;
    @Configurable("Total stop loss (% of account)")
    public double slPct = 1;
   
    private double balance;
    private double TPbalance;
    private double SLbalance;
    private double Total;
   

    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();
       
        double Total = 0;
        for (IOrder ord : engine.getOrders()) {
            Total += context.getAccount().getBaseEquity();
        }
       
        //engine.submitOrder("ord1", Instrument.EURUSD, IEngine.OrderCommand.SELL, 1);
       
        // set current balance level to equity without current orders profit/loss
        balance = context.getAccount().getBaseEquity();
        console.getOut().println("First balance "+(new DecimalFormat("#.#######")).format(balance));
       
    }

    public void onAccount(IAccount account) throws JFException {
        double Total = 0;
        //Total = context.getAccount().getBaseEquity();
        console.getOut().println("Total "+ Total);
        for (IOrder ord : engine.getOrders()) {
            Total += context.getAccount().getBaseEquity();
        }
        Total = context.getAccount().getBaseEquity();
        console.getOut().println("Total2 "+ Total);
        TPbalance = ((balance * 0.01 * tpPercent)+balance);
        SLbalance = ((- balance * 0.01 * slPct)+balance);
        console.getOut().println("TPbalance "+TPbalance);
        console.getOut().println("SLbalance "+SLbalance);
        if (    (Total > TPbalance) ||
                (Total < SLbalance )) {
            for (IOrder order : engine.getOrders()) {
                if(order.getState() != IOrder.State.CLOSED && order.getState() != IOrder.State.CANCELED) {
                    order.close();
                }
            }
           
            balance = account.getBaseEquity();
            TPbalance = ((balance * 0.01 * tpPercent)+balance);
            SLbalance = ((- balance * 0.01 * slPct)+balance);
            console.getOut().println("RESET balance "+(new DecimalFormat("#.#######")).format(balance));
            console.getOut().println("TPbalance After RESET "+ TPbalance);
            console.getOut().println("SLbalance After RESET "+ SLbalance);
        }
       
    }

    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 {
    }
   
    int counter = 0;
    private String getLabel(Instrument instr) {
        String label = instr.name();
        label = label + (counter++);
        label = label.toUpperCase();
        return label;
    }
}




 
 Post subject: Re: Equity Change Strategy Post rating: 0   New post Posted: Tue 01 Oct, 2013, 09:39 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
Chubbly wrote:
For some reason the if statement that calculates if the current equity is greater or less than the TP or SL + and - values is not working
Could you please provide a case when the strategy does not work as expected?


 
 Post subject: Re: Equity Change Strategy Post rating: 0   New post Posted: Tue 01 Oct, 2013, 11:33 

User rating: 3
Joined: Sat 04 May, 2013, 03:34
Posts: 33
Location: CanadaCanada
API Support wrote:
Chubbly wrote:
For some reason the if statement that calculates if the current equity is greater or less than the TP or SL + and - values is not working
Could you please provide a case when the strategy does not work as expected?


I run the code with a DEMO account

Starting Base Equity
80738.89


I select values of 1% when the strategy starts


    @Configurable("Total take profit (% of account)")
    public double tpPercent = 1;
    @Configurable("Total stop loss (% of account)")
    public double slPct = 1;



The Strategy puts out the following message

Quote:
10:16:49 SLbalance 79931.5011
10:16:49 TPbalance 81546.2789
10:16:49 Total2 80738.89
10:16:49 Total 0.0
10:16:49 First balance 80738.89


These values were calculated on the following lines
      balance = context.getAccount().getBaseEquity();
        console.getOut().println("First balance "+(new DecimalFormat("#.#######")).format(balance));
         
    }
 
    public void onAccount(IAccount account) throws JFException {
        double Total = 0;
        //Total = context.getAccount().getBaseEquity();
        console.getOut().println("Total "+ Total);
        for (IOrder ord : engine.getOrders()) {
            Total += context.getAccount().getBaseEquity();
        }
        Total = context.getAccount().getBaseEquity();
        console.getOut().println("Total2 "+ Total);
        TPbalance = ((balance * 0.01 * tpPercent)+balance);
        SLbalance = ((- balance * 0.01 * slPct)+balance);
        console.getOut().println("TPbalance "+TPbalance);
        console.getOut().println("SLbalance "+SLbalance);


From the message we see that it calculated what the Base equity would be at -1% (SLbalance 79931.5011) and +1% (TPbalance 81546.2789)
When either of these values are reached the the strategy is supposed to close all positions and start over and calculate new +1% and -1% values

   if (    (Total > TPbalance) ||
           (Total < SLbalance )) {
            for (IOrder order : engine.getOrders()) {
                if(order.getState() != IOrder.State.CLOSED && order.getState() != IOrder.State.CANCELED) {
                    order.close();

I forced the Equity down by purposely losing trades to 78500 but the if statement is not triggered.

If you run the code you will see this


 
 Post subject: Re: Equity Change Strategy Post rating: 0   New post Posted: Tue 01 Oct, 2013, 12:06 
User avatar

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

In the past I had issues to compare an order's SL/TP with an actual tick's price.
I ended up using Double.compare():
if (Double.compare(anOrder.getStopLossPrice(),0) == 0) {

}


You could give it a try to modify the code to use the mentioned function, but maybe this is not relevant at all...


 
 Post subject: Re: Equity Change Strategy Post rating: 3   New post Posted: Tue 01 Oct, 2013, 12:47 
User avatar

User rating: 94
Joined: Mon 06 Feb, 2012, 12:22
Posts: 357
Location: Portugal, Castelo Branco
Hi...

I see some problem logic with your strategy:

for (IOrder ord : engine.getOrders()) {
Total += context.getAccount().getBaseEquity();  //why this ??? you are adding again the base equity on each order...
}
Total = context.getAccount().getBaseEquity(); //and after this ???


In my view you will need to use getEquity() and getBaseEquity() to see the diference... see -> https://www.dukascopy.com/client/javadoc ... count.html.

Also, you need to take in consideration that the values returned from this functions can have some delay... the javadoc refer 5 seconds.

I hope that helps

Trade well

JL


 
 Post subject: Re: Equity Change Strategy Post rating: 0   New post Posted: Tue 01 Oct, 2013, 14:07 

User rating: 3
Joined: Sat 04 May, 2013, 03:34
Posts: 33
Location: CanadaCanada
Hi

The reason I am using getBaseEquity() is because I do not open Profit/Loss to be calculated in. I run a basket of 10 strategies, when then the total equity reaches a value I want to close all positions to lock in profits or to stop the strategies from losing more equity. So this way I can look at the 10 strategies as a single group instead of as individual strategies.

So I want to get the Base Equity at the start and constantly compare the change to see if the target TP Equity or SL Equity have been meet.

I commented out those lines but then the Total value becomes 0 and the strategy just closes all positions immediately

for (IOrder ord : engine.getOrders()) {
//Total += context.getAccount().getBaseEquity(); 
}
//Total = context.getAccount().getBaseEquity();


 
The Best Answer  Post subject: Re: Equity Change Strategy Post rating: 4   New post Posted: Tue 01 Oct, 2013, 14:32 
User avatar

User rating: 94
Joined: Mon 06 Feb, 2012, 12:22
Posts: 357
Location: Portugal, Castelo Branco
Hi:

Support will correct me if i'm wrong but:

getBaseEquity() returns the value of equity *without* taking in consideration the loss/profit of open orders

getEquity() returns the actual value of equity taking in consideration open orders and their profit/loss.

javadoc:

getEquity

double getEquity()
Returns current equity. Value returned by this function is for information purposes and can be incorrect right after order changes, as it is updated about every 5 seconds
Returns:
equity
getBaseEquity

double getBaseEquity()
Returns current base equity (No open Profit/Loss).
Value returned by this function is for information purposes and can be incorrect right after order changes, as it is updated about every 5 seconds.
Returns:
base equity - equity without open positions' profit/loss

So, you can see you are calculating always the equity value without considering the open orders.

In my view you use getBaseEquity() to calculate the SL and TP profit equity values and them compare with getEquity() values. This way you can compare sl/tp value with the real change on equity value.

Can you see the difference ?

Trade well

JL


 
 Post subject: Re: Equity Change Strategy Post rating: 0   New post Posted: Tue 01 Oct, 2013, 14:54 

User rating: 3
Joined: Sat 04 May, 2013, 03:34
Posts: 33
Location: CanadaCanada
Ok, I see the difference now. I have made the change you suggested and it seems to be working now
Thanks for the help

        double Total = 0;
        //Total = context.getAccount().getEquity();
        //console.getOut().println("Total "+ Total);
        for (IOrder ord : engine.getOrders()) {
            //Total += context.getAccount().getEquity();
        }
        Total = context.getAccount().getEquity();//This line changed to getEquity
        console.getOut().println("Total "+ Total);
        console.getOut().println("TPbalance "+TPbalance);
        console.getOut().println("SLbalance "+SLbalance);
        console.getOut().println("First balance "+(new DecimalFormat("#.#######")).format(balance));

        if (    (Total > TPbalance) ||
                (Total < SLbalance )) {
            for (IOrder order : engine.getOrders()) {
                if(order.getState() != IOrder.State.CLOSED && order.getState() != IOrder.State.CANCELED) {
                    order.close();
                }
            }
           


 

Jump to:  

  © 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