package jforex.test;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

import com.dukascopy.api.*;
import com.dukascopy.api.IEngine.OrderCommand;

/**
 * The strategy on its start creates an order. Then it
 * tries to close it while it is CREATED -> should raise exception.
 * Thereafter it tries to close it while it is FILLED -> this 
 * should raise no exception.
 *
 */

@RequiresFullAccess
public class OrderErrorMessage implements IStrategy {

	private IConsole console;
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") {{setTimeZone(TimeZone.getTimeZone("GMT"));}};
	DecimalFormat df = new DecimalFormat("0.00000");	
	
	@Override
	public void onStart(IContext context) throws JFException {
		
		console = context.getConsole();		
		IOrder o = context.getEngine().submitOrder("order", Instrument.EURUSD, OrderCommand.BUY, 0.001);
		tryClose(o);
		o.waitForUpdate(1000); //wait OPENED
		o.waitForUpdate(1000); //wait FILLED
		tryClose(o);

	}
	
	private void tryClose (IOrder o){
		
		console.getOut().println("try close");
		try{
			o.close();
		} catch( JFException e){
			console.getErr().println(e);
			String errorStr = String.format("order: %s, fillTime=%s, creationTime=%s, openPrice=%s, state=%s",
					o.toString(), sdf.format(o.getFillTime()),sdf.format(o.getCreationTime()),df.format(o.getOpenPrice()),
					o.getState()); 
			console.getErr().println(errorStr);
		}
	}

	@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 {
		console.getOut().println(sdf.format(message.getCreationTime()) + " " +message);
	}

	@Override
	public void onAccount(IAccount account) throws JFException {}

	@Override
	public void onStop() throws JFException {
		
	}

}
