
package jforex.test;

import java.util.concurrent.Callable;

import com.dukascopy.api.IAccount;
import com.dukascopy.api.IBar;
import com.dukascopy.api.IConsole;
import com.dukascopy.api.IContext;
import com.dukascopy.api.IMessage;
import com.dukascopy.api.IStrategy;
import com.dukascopy.api.ITick;
import com.dukascopy.api.Instrument;
import com.dukascopy.api.JFException;
import com.dukascopy.api.Period;

public class ConcurrentThreads implements IStrategy {
    private IConsole console;
    Thread threadOne;
    Thread threadTwo;
    
    @Override
    public void onStart(IContext context) throws JFException {
        console = context.getConsole();
        final IContext finalContext = context; 
        
        //run the task in a different thread:
        final NamedTask taskOne = new NamedTask("taskOne");
        threadOne = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    finalContext.executeTask(taskOne);
                } catch (Exception e) {
                    console.getErr().println(Thread.currentThread().getName() + " " + e);
                }
            }
        });
        threadOne.start();
        
        final NamedTask taskTwo = new NamedTask("taskTwo");
        threadTwo = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    finalContext.executeTask(taskTwo);
                } catch (Exception e) {
                    console.getErr().println(Thread.currentThread().getName() + " " + e);
                }
            }
        });
        threadTwo.start();       
        
    }

    private class NamedTask implements Callable<String> {
        private final String taskName;

        public NamedTask(String taskName) {
            this.taskName = taskName;
        }
        public String call() throws Exception {
        	console.getOut().println("NamedTask name: " + taskName); 
        	int ticker = 0;
        	while (ticker < 100){
        		ticker++;
        		console.getInfo().println("NamedTask: " + taskName + " - ticker:" + ticker + " <*><*><*><*><*><*><*><*><*><*>");
        		Thread.sleep(1000);
        	}
            return taskName;
        }
    }

    @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 {
    	threadTwo.interrupt();
    	threadTwo.interrupt();
    }

}