///By JP7 from Dukascopy Forum///

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

public class UseofLeverage_Percentage_Closure implements IStrategy {


    private IEngine engine;
    private IConsole console;
    private IHistory history;
    private IContext context;
    @Configurable("Use of Leverage drop % closure")
    public double tpPercent = 30.00;

    private double balance;
    

    public void onStart(IContext context) throws JFException {
        this.engine = context.getEngine();
        this.console = context.getConsole();
        this.setHistory(context.getHistory());
        context.getConsole();// on start
        this.engine = context.getEngine();
        this.console = context.getConsole();
        this.history = context.getHistory();
        this.context = context;

        // remove this line with // after testing
        engine.submitOrder("ord1", Instrument.EURUSD, IEngine.OrderCommand.SELL, 0.7); //
        //
        
        balance = context.getAccount().getEquity();
        console.getOut().println("initial balance "+(new DecimalFormat("#.#######")).format(balance));
        
    }

    public void onAccount(IAccount account) throws JFException {
 
        double UseofLeverage = account.getUseOfLeverage();

        console.getOut().println("UseofLeverage"+(UseofLeverage));

        
        if (UseofLeverage >= tpPercent) {
            for (IOrder order : engine.getOrders()) {
                if(order.getState() != IOrder.State.CLOSED && order.getState() != IOrder.State.CANCELED) {
                    order.close();
                    console.getOut().println("Leverage % Reached "+(UseofLeverage)+" %");

                }
            }
            
            balance = account.getEquity();
            console.getOut().println("Use of Leverage % Reached "+(new DecimalFormat("#.#######")).format(balance));
                    context.stop();
        }
        
    }


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

    public IHistory getHistory() {
        return history;
    }

    public void setHistory(IHistory history) {
        this.history = history;
    }
    public void setContext(IContext context) {
        this.context = context;
    }

}