package singlejartest;

import java.util.List;

import com.dukascopy.api.*;
import com.dukascopy.api.IEngine.OrderCommand;
import com.dukascopy.api.IOrder.State;

public class SimpleScalpingStrategy implements IStrategy {
	
	public Instrument instrument = Instrument.EURUSD;	
	public double amount = 0.1;
	public int stopLossPips = 10;
	public int takeProfitPips = 3;
	IOrder ordreBuy, ordreSell = null;
	
	
	private IEngine engine;	
	private IHistory history;
	
	public void onStart(IContext context) throws JFException {
		this.engine = context.getEngine();		
		this.history = context.getHistory();
   	}

	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 {	
		if(ordreBuy.getState() == State.FILLED){
			ordreBuy.setStopLossPrice(ordreBuy.getOpenPrice()-stopLossPips*0.0001);
			ordreBuy.setTakeProfitPrice(ordreBuy.getOpenPrice()+takeProfitPips*0.0001);
		}
		if(ordreSell.getState() == State.FILLED){
			ordreSell.setStopLossPrice(ordreSell.getOpenPrice()+stopLossPips*0.0001);
			ordreSell.setTakeProfitPrice(ordreSell.getOpenPrice()+takeProfitPips*0.0001);
		}
	}
	
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar)throws JFException {  
    	IBar prevBar = history.getBar(this.instrument, Period.FIVE_MINS, OfferSide.BID, 1); 
    	double haut = prevBar.getHigh();
    	double bas = prevBar.getLow();
    	double priceBUY = haut+0.00050;
    	double priceSELL = bas-0.00050;
    	List<IOrder> ordres = engine.getOrders();
		if(ordres.isEmpty()){
	    	ordreBuy = engine.submitOrder("BUYSTOP", Instrument.EURUSD, OrderCommand.BUYSTOP, amount, priceBUY);
	    	ordreSell = engine.submitOrder("SELLSTOP", Instrument.EURUSD, OrderCommand.SELLSTOP, amount, priceSELL);
		}
    	if(ordreBuy.getState() != null || ordreSell.getState() != null){
    		if(ordreBuy.getState() == State.OPENED){
    			ordreBuy.setOpenPrice(priceBUY);
    		}
    		if(ordreSell.getState() == State.OPENED){
    			ordreSell.setOpenPrice(priceSELL);
    		}
    		if(ordreBuy.getState() == State.FILLED && ordreSell.getState() == State.OPENED){
    			engine.getOrder("SELLSTOP").close();
    		}
    		if(ordreSell.getState() == State.FILLED && ordreBuy.getState() == State.OPENED){
    			engine.getOrder("BUYSTOP").close();
    		}
    	}
    }
    
}














