package jforex.orders;

import java.math.BigDecimal;
import com.dukascopy.api.*;
import static com.dukascopy.api.Instrument.*;

public class OrderCommissionsCompensate implements IStrategy {
    
    @Configurable("Order amount")
    public double amount = 0.1;
    
    private static final int MILLION = 1000000;
    
    private IEngine engine;
    private IConsole console;
    private IHistory history;
    
    @Override
    public void onStart(IContext context) throws JFException {
        engine = context.getEngine();
        console = context.getConsole();
        history = context.getHistory();
        
        double totalCommission = 0;
        for(IOrder order : engine.getOrders()){
            totalCommission += order.getCommissionInUSD();
        }        
        double openPrice = history.getLastTick(EURUSD).getBid();
        double tpPrice = openPrice + totalCommission /(amount * MILLION);
        print("Total commission = %.2fUSD,  tpPrice=%.5f, tp in pips=%.1f",
                totalCommission, tpPrice, ( tpPrice - openPrice) / EURUSD.getPipValue());
        engine.submitOrder("compensateOrder", EURUSD, IEngine.OrderCommand.BUY, amount, openPrice, 10, 0, roundToPippette(tpPrice, EURUSD));
    }
    
    private void print(Object o){
        console.getOut().println(o);
    }
    
    private void print(String message, Object... args){
        print(String.format(message,args));
    }
    
    private static double roundToPippette(double amount, Instrument instrument) {
        return round(amount, instrument.getPipScale() + 1);
    }
    
    private static double round(double amount, int decimalPlaces) {
        return (new BigDecimal(amount)).setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    @Override
    public void onTick(Instrument instrument, ITick tick) throws JFException {}

    @Override
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {}

    @Override
    public void onMessage(IMessage message) throws JFException {}

    @Override
    public void onAccount(IAccount account) throws JFException {}

    @Override
    public void onStop() throws JFException {}

}
