package jforex.strategies;

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

public class GlobalEquityClosure     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;
    

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

    public void onAccount(IAccount account) throws JFException {
        double totalPL = 0;
        for (IOrder ord : engine.getOrders()) {
            totalPL += ord.getProfitLossInAccountCurrency();
        }
        if (    (totalPL > balance * 0.01 * tpPercent) ||
                (totalPL < - balance * 0.01 * slPct) ) {
            for (IOrder order : engine.getOrders()) {
                if(order.getState() != IOrder.State.CLOSED && order.getState() != IOrder.State.CANCELED) {
                    order.close();
                }
            }
            
            balance = account.getEquity();
            console.getOut().println("new balance "+(new DecimalFormat("#.#######")).format(balance));
        }
        
    }

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