package com.pixelka.forex;

import java.util.*;
import com.dukascopy.api.*;
public class Example implements IStrategy {
    
  
    private IContext context = null;
    private IEngine engine = null;
    private IChart chart = null;
    private IHistory history = null;
    private IIndicators indicators = null;
    private IConsole console = null;
    Public double volume = 0.027696;
    Public int profitLimit;
    Public int lossLimit;
    Public double bidPrice;
    Public double askPrice;
    Public double accountEquity;
    Public int tradeDate;
    Public Instrument instrument;
    public Period selectedPeriod = Period.TEN_MINS;
    public int  takeProfit = 100;
    public int  stopLoss = 30;
    public int  TP2 = 19;
    public int  SL2 = 18;
    @Configurable("VaR in percentage")
    public double  VaR = 0.1;
    @Configurable("VaR Multiplier")
    public int  VaRMultiplier = 2;
    @Configurable("Start Equity")
    public double  startEquity = 10000;
    @Configurable("Maximum Duraration (Hr)")
    public double  MaxDuration = 66;
    Public double MaxDurationMills = 0;
    @Configurable("Maximum Volume (million)")
    public double  MaxVol = 5;
  
    public void onStart(IContext context) throws JFException {
        this.context = context;  
        engine = context.getEngine();
        indicators = context.getIndicators();
        history = context.getHistory();
        console = context.getConsole();
        indicators = context.getIndicators();
        instrument = Instrument.EURUSD;
        Set subscribedInstruments = new HashSet();
            subscribedInstruments.add(Instrument.EURUSD);
            context.setSubscribedInstruments(subscribedInstruments);
    }

    public void onStop() throws JFException {
    }


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

    }


// DETECTION OF LONG OR SHORT TRADE
    protected int islong(Instrument instrument) throws JFException {
        int counter = 0;
        for (IOrder order : engine.getOrders(instrument)) {
            if (order.isLong()) {
                counter++;
            }
        }
        return counter;
    }
// OPEN POSITION COUNTER
    protected int positionsTotal(Instrument instrument) throws JFException {
        int counter = 0;
        for (IOrder order : engine.getOrders(instrument)) {
            if (order.getState() == IOrder.State.FILLED) {
                counter++;
            }
        }
        return counter;
    }

    protected String getLabel(Instrument instrument) {
        String label = instrument.name();        
        long time = new java.util.Date().getTime();
        label = label.substring(0, 2) + label.substring(3, 5);
        label = label + time;
        label = label.toLowerCase();
        return label;
    }

    public void onBar(Instrument instrument, Period period, IBar askbar, IBar bidbar) throws JFException {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); 
        calendar.setTimeInMillis ( bidbar.getTime()); 

        int Heures           = calendar.get ( Calendar.HOUR_OF_DAY ) ;
        int Minutes          = calendar.get ( Calendar.MINUTE ) ;      
        int HeuresMinutes    = ( Heures * 100 ) + Minutes ;  
        int Day              = calendar.get (Calendar.DAY_OF_WEEK ) ;          
        
// TRADE ENTRY TIME RESTRICTIONS
                  
       if( (instrument != this.instrument) || (askbar.getVolume() == 0) ) return;
       if(period == selectedPeriod ){

        profitLimit = takeProfit;
        lossLimit = stopLoss;
        

// VOLUME SETTINGS
        if( accountEquity < startEquity) {
                volume = ( (VaR * accountEquity ) / ( instrument.getPipValue() * stopLoss) / 1000000 );}
        else if( accountEquity > startEquity) {
                volume = ( ( ( (VaRMultiplier * VaR) * (accountEquity - startEquity) ) / ( instrument.getPipValue() * stopLoss) / 1000000 ) + 
                ( (VaR * startEquity ) / ( instrument.getPipValue() * stopLoss) / 1000000 ) );}  
       if (volume > MaxVol){
            volume = MaxVol;
          }  
                                 
// TRADE ENTRY PARAMETERS     


// TRADE ENTRY LOGIC                                                   

        } // closes position == 0
    } // closes period == selectperiod

  
// CLOSING POSITION AFTER PRE-DETERMINED DURATION
       if(period == selectedPeriod ){
        for (IOrder orderInMarket : engine.getOrders()) {
            Calendar tradeDate = Calendar.getInstance(TimeZone.getTimeZone("UTC")); 
            tradeDate.setTimeInMillis ( orderInMarket.getFillTime() );
            MaxDurationMills = (MaxDuration*60*60*1000);
 
                 if ((orderInMarket.getState() == IOrder.State.FILLED) 
	            && (bidbar.getTime() >= (orderInMarket.getFillTime() + MaxDurationMillsFri) ) ) {
 //                   orderInMarket.close();
                  if (orderInMarket.isLong()) {
                        orderInMarket.setStopLossPrice(askPrice - instrument.getPipValue() * SL2);
                        orderInMarket.setTakeProfitPrice(askPrice + instrument.getPipValue() * TP2);}
                    else if (!orderInMarket.isLong()) {
                        orderInMarket.setStopLossPrice (bidPrice + instrument.getPipValue() * SL2);
                        orderInMarket.setTakeProfitPrice(bidPrice - instrument.getPipValue() * TP2);
                    }

                }
           }
                           
} // closes onBar

  public void onMessage(IMessage message) throws JFException {        
        if (message != null && message.getType() == IMessage.Type.ORDER_CLOSE_OK) {            
            IOrder lastOne = message.getOrder();            
            double profitsLoss = lastOne.getProfitLossInPips();            
            console.getOut().println("Order : "+lastOne.getLabel()+ " "+ lastOne.getOrderCommand()+ " Pips: "+profitsLoss);
                       
        }
}
     
// TRADE EXECUTION MECHANICS
  @Override
   public void onAccount(IAccount account) throws JFException {
   accountEquity = account.getEquity() ;    
   }
    public void sell(Instrument instrument, IEngine engine, int takeProfitPipLevel, int endLossPipLevel, double volumeParam)  throws JFException {
        
        engine.submitOrder(getLabel(instrument), instrument, IEngine.OrderCommand.SELL, volumeParam, 0, 3, bidPrice
                        + instrument.getPipValue() *endLossPipLevel, bidPrice - instrument.getPipValue() * takeProfitPipLevel);
    

     } 
     
      public void buy(Instrument instrument, IEngine engine, int takeProfitPipLevel, int endLossPipLevel, double volumeParam)  throws JFException {
        
         engine.submitOrder(getLabel(instrument), instrument, IEngine.OrderCommand.BUY, volumeParam, 0, 3, askPrice
                        - instrument.getPipValue() * endLossPipLevel, askPrice + instrument.getPipValue() * takeProfitPipLevel);
     

     } 
}