-- Id: 17701
-- More information about this indicator can be found at:
-- http://fxcodebase.com/code/viewtopic.php?f=17&t=64479

--+------------------------------------------------------------------+
--|                               Copyright © 2018, Gehtsoft USA LLC |
--|                                            http://fxcodebase.com |
--+------------------------------------------------------------------+
--|                                      Developed by : Mario Jemic  |
--|                                          mario.jemic@gmail.com   |
--+------------------------------------------------------------------+
--|                                 Support our efforts by donating  |
--|                                    Paypal: https://goo.gl/9Rj74e |
--|                    BitCoin : 15VCJTLaz12Amr7adHSBtL9v8XomURo9RF  |
--|                BitCoin Cash: 1BEtS465S3Su438Kc58h2sqvVvHK9Mijtg  |
--|           Ethereum : 0x8C110cD61538fb6d7A2B47858F0c0AaBd663068D  |
--|                   LiteCoin : LLU8PSY2vsq7B9kRELLZQcKf5nJQrdeqwD  |
--+------------------------------------------------------------------+

function Init()
    indicator:name("Cointegration Indicator");
    indicator:description("");
    indicator:requiredSource(core.Bar);
    indicator:type(core.Oscillator);	
	
	indicator.parameters:addGroup(  "Calculation");
	
	indicator.parameters:addInteger("Trailing", "Trailing Period", "" , 34);
	indicator.parameters:addDouble("Deviation", "Deviation", "" , 2);
	indicator.parameters:addInteger("Period", "MA Period", "" , 34);
	
	indicator.parameters:addString("Method", "Data Selector", "" , "Available");
    indicator.parameters:addStringAlternative("Method", "Available data", "" , "Available");
    indicator.parameters:addStringAlternative("Method", "Trailing", "" , "Trailing");
	indicator.parameters:addStringAlternative("Method", "Select by user", "" , "User");
	
	
    Add(1, "EUR/SUD");
	Add(2, "EUR/SUD");
	Add(3, "EUR/SUD");
    Add(4, "EUR/SUD");
	Add(5, "EUR/SUD");
	Add(6, "EUR/SUD");
	Add(7, "EUR/SUD");
	Add(8, "EUR/SUD");
	Add(9, "EUR/SUD");
	Add(10, "EUR/SUD");
	
	
	indicator.parameters:addGroup(  "Line Style");
	
	indicator.parameters:addColor("color", "Line Color", "", core.rgb(0, 0, 255));
    indicator.parameters:addInteger("width", "Line Width", "", 1, 1, 5);
    indicator.parameters:addInteger("style" , "Line Style", "", core.LINE_SOLID);
    indicator.parameters:setFlag("style", core.FLAG_LEVEL_STYLE);
	
	indicator.parameters:addColor("color1", "Top Line Color", "", core.rgb(255, 0, 0));
    indicator.parameters:addInteger("width1", "Line Width", "", 1, 1, 5);
    indicator.parameters:addInteger("style1" , "Line Style", "", core.LINE_SOLID);
    indicator.parameters:setFlag("style1", core.FLAG_LEVEL_STYLE);
	
	
	indicator.parameters:addColor("color2", "Bottom Line Color", "", core.rgb(0, 255, 0));
    indicator.parameters:addInteger("width2", "Line Width", "", 1, 1, 5);
    indicator.parameters:addInteger("style2" , "Line Style", "", core.LINE_SOLID);
    indicator.parameters:setFlag("style2", core.FLAG_LEVEL_STYLE);
	
	indicator.parameters:addColor("color3", "MA Line Color", "", core.rgb(128, 128, 128));
    indicator.parameters:addInteger("width3", "Line Width", "", 1, 1, 5);
    indicator.parameters:addInteger("style3" , "Line Style", "", core.LINE_SOLID);
    indicator.parameters:setFlag("style3", core.FLAG_LEVEL_STYLE);
	
end

 
function Add(id, Instrument)
   
     indicator.parameters:addGroup(  id.. ". Instrument");
    if id == 1 then
    indicator.parameters:addBoolean("On"..id, "Use this Instrument", "", true);
	else
	 indicator.parameters:addBoolean("On"..id, "Use this Instrument", "", false);
	end
	
   	indicator.parameters:addString("Instrument"..id, "Instrument", "", Instrument);
    indicator.parameters:setFlag("Instrument"..id, core.FLAG_INSTRUMENTS );
    indicator.parameters:addDouble("Weight"..id, "Weight", "", 100);

  
end 
 
 
local dayoffset,weekoffset;
local Weight={};
local Source ={};
local Instrument={};
local Method;
local Trailing;
local source = nil;
local loading={}; 
local p={};
local Number ; 
local Cointegration;
local Top,Bottom,MA;
local Deviation;
local Period;
local pattern = "([^;]*);([^;]*)";
local db;
local start={};
local PipCost={};
-- Routine
function Prepare(nameOnly)   
	  
    source = instance.source; 
	dayoffset = core.host:execute("getTradingDayOffset");
    weekoffset = core.host:execute("getTradingWeekOffset");	
	Method= instance.parameters.Method;
	Trailing= instance.parameters.Trailing;
	Deviation= instance.parameters.Deviation;
	Period= instance.parameters.Period;
	
 
	Number=0;

    local name = profile:id() .. "(" .. source:name() .. ")";
	instance:name(name);
	if nameOnly then
		return;
	end	
	local i;
		for  i = 1, 10, 1 do
			 if instance.parameters:getBoolean ("On"..i) then
			 Number=Number+1;
			 Instrument[Number]= instance.parameters:getString("Instrument" .. i);
			 Weight[Number]= instance.parameters:getDouble("Weight" .. i);
			 Source[Number] = core.host:execute("getSyncHistory",Instrument[Number], source:barSize(), source:isBid(), 0, 200+i, 100+i);			
			loading[Number]=true;
			
			PipCost[Number] = core.host:findTable("offers"):find("Instrument", Instrument[Number]).PipCost;
		 
		  end
	end
	
	require("storagedb");
    db = storagedb.get_db(name);	
	db:put("Date", source:date(source:first()));  
	
	Cointegration = instance:addStream("Cointegration", core.Line, name, "Cointegration", instance.parameters.color, source:first());
    Cointegration:setPrecision(math.max(2, instance.source:getPrecision()));
	Cointegration:setWidth(instance.parameters.width);
    Cointegration:setStyle(instance.parameters.style);
	
	
	Top = instance:addStream("Top", core.Line, name, "Top", instance.parameters.color1, source:first());
    Top:setPrecision(math.max(2, instance.source:getPrecision()));
	Top:setWidth(instance.parameters.width1);
    Top:setStyle(instance.parameters.style1);
	
	Bottom = instance:addStream("Bottom", core.Line, name, "Bottom", instance.parameters.color2, source:first());
    Bottom:setPrecision(math.max(2, instance.source:getPrecision()));
	Bottom:setWidth(instance.parameters.width2);
    Bottom:setStyle(instance.parameters.style2);
	
	MA = instance:addStream("MA", core.Line, name, "MA", instance.parameters.color3, source:first());
    MA:setPrecision(math.max(2, instance.source:getPrecision()));
	MA:setWidth(instance.parameters.width3);
    MA:setStyle(instance.parameters.style3);
	
	core.host:execute("addCommand", 1,  profile:id() .. " Select Start Time");
  
end

-- Indicator calculation routine
-- TODO: Add your code for calculation output values
function Update(period, mode)

    local Start=1;
    core.host:execute ("removeAll");
	
    local Flag = false;
  
	for i= 1, Number, 1 do
	
		
			p[i]= Initialization(period,i)	
			
	
		if loading[i] or p[i]== false then		
		Flag=true;
		end
	end
	
	
		if Method =="User" then
					local Date= tonumber(db:get("Date", 0));  
					if Date==0 then
					return;
					end	
					Start= core.findDate (source, Date, false); 
					if Start==-1 then
					return;
					end
					
					for i= 1, Number, 1 do					
					start[i]= Initialization(Start,i);						
					end
					
		 end
		
	
	if Flag then
	return;
	end	
	
	Cointegration[period]=0;
	 
	for i= 1, Number, 1 do 
	
	    if Method == "Available" then
			if p[i] > Source[i].close:first() then
			Cointegration[period]=Cointegration[period] + (((( Source[i].close[p[i]]-Source[i].close[Source[i].close:first()])/Source[i]:pipSize())*PipCost[i])*Weight[i]);
			end 
		elseif Method == "Trailing" then		
		   if p[i] > Trailing then
			Cointegration[period]=Cointegration[period] + ((((Source[i].close[p[i]]-Source[i].close[p[i] - Trailing+1 ])/Source[i]:pipSize())*PipCost[i])*Weight[i]);
			end 			
		else
		
		    Cointegration[period]=Cointegration[period] + (((( Source[i].close[p[i]]-Source[i].close[start[i]])/Source[i]:pipSize())*PipCost[i])*Weight[i]);
		end
		
		
	end
	
	if period <Period then
    return;
	end
	
	MA[period]= mathex.avg(Cointegration, period-Period+1, period);	
	local Delta= mathex.stdev (Cointegration, period-Period+1, period);	
	Top[period]= MA[period]+Delta*Deviation;
	Bottom[period]= MA[period]-Delta*Deviation;
	
	 if  period== source:size()-1 and  Method =="User" then
	 local min,max=mathex.minmax(MA, source:first(), source:size()-1);
     core.host:execute ("drawLine", 1, source:date(Start), min, source:date(Start), max , core.COLOR_LABEL );
     end					 
	
  
 
end




function   Initialization(period,id)

    local Candle;
    Candle = core.getcandle(source:barSize(), source:date(period), dayoffset, weekoffset);
  
    if loading[id] or Source[id]:size() == 0  then
        return false;
    end

    
    if period < source:first() then
        return false;
    end

    local P = core.findDate(Source [id], Candle, false);
	 

    -- candle is not found
    if P < 0    then
        return false;
	else return P;	
    end
			
end	




-- the function is called when the async operation is finished
function AsyncOperationFinished(cookie, success, message)
     local j;	 
	local Flag = false;	
	local Count=0;	
	
	
	
    for j = 1, Number, 1 do
		
			  if cookie == (100+j) then
			  loading[j] = true;
		      elseif  cookie == (200+j) then
			  loading[j] = false; 	 
              end
			  
		if loading[j] then
		Count=Count+1;
		Flag=true;
		end	 
   end
   
   
   if cookie == 1 then 
	 
	local Level, Date = string.match(message, pattern, 0);
	
	 
	db:put("Date", tostring(Date));  
	
	end
	
		  
		if Flag then
		core.host:execute ("setStatus", " Loading ".. (Number-Count) .."/" .. Number);
		else
		core.host:execute ("setStatus", " Loaded ".. (Number-Count) .."/" .. Number);
		instance:updateFrom(0);	
		end
			  
	    
   
        
		return core.ASYNC_REDRAW ;
end
 


