package RSXTest;

import com.dukascopy.api.*;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Date;

public class RSXDemoStrat implements IStrategy {
    public IContext context;
    public IEngine engine;
    public IAccount account;
    public IConsole console;
    public IIndicators indicators;
    
    public Instrument instrument;
    public Period period;

    private String csvData;

    private int barCount = 0;

    public void onStart(IContext context) throws JFException {
        this.context = context;
        this.engine = context.getEngine();
        this.account = context.getAccount();
        this.console = context.getConsole();
        this.indicators = context.getIndicators();

        this.indicators.registerCustomIndicator(RSXOscillator.class);

        this.csvData = "\"Date\",\"Instrument\",\"Period\",\"Fast Trend\"\n";
    }

    public void onAccount(IAccount account) throws JFException { }

    public void onMessage(IMessage message) throws JFException { }

    public void onStop() throws JFException {
        String filePath = "C:\\temp\\ht\\";
        filePath += "data.csv";
        this.WriteFile(this.csvData, filePath);
    }

    public void onTick(Instrument instrument, ITick tick) throws JFException { }

    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
        if (this.instrument == instrument && this.period == period && askBar.getVolume() > 0) {
            Object[] rsxArray = this.indicators.calculateIndicator(instrument, period, new OfferSide[] { OfferSide.BID }, "RSXOscillator",
                    new IIndicators.AppliedPrice[] { IIndicators.AppliedPrice.CLOSE }, new Object[] { 21 }, Filter.WEEKENDS, 21, bidBar.getTime(), 0);

            double[] rsx = (double[])rsxArray[3];

            this.csvData += "\"" + new Date(bidBar.getTime()).toGMTString() + "\",\"" + instrument + "\",\"" + period + "\",\"" + rsx[rsx.length - 1] + "\"\n";
        }
    }

    private void WriteFile(String content, String path) {
        try {
            FileWriter fs = new FileWriter(path);
            BufferedWriter out = new BufferedWriter(fs);
            out.write(content);
            out.close();
        } catch (Exception e){
            System.err.println("Error: " + e.getMessage());
        }
    }
}
