Function Collection

Moderator: admin

Round

Postby Apprentice » Fri Dec 21, 2012 5:27 am

Code: Select all
function round(num, idp)
  if idp and idp>0 then
    local mult = 10^idp
    return math.floor(num * mult + 0.5) / mult
  end
  return math.floor(num + 0.5)
end
User avatar
Apprentice
FXCodeBase: Confirmed User
 
Posts: 36341
Joined: Thu Dec 31, 2009 11:59 am
Location: Zagreb, Croatia

TimeZones

Postby Apprentice » Mon Dec 31, 2012 6:56 am

Code: Select all
function loadTimeZones()
    local tzs = win32.getTimeZonesList();
    local out = {};
    local i;
    for i = 1, #tzs, 1 do
        local name = win32.getRegistry("HKLM Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\" .. tzs[i], "Display");
        out[i] = {};
        out[i].id = tzs[i];
        out[i].name = name;
    end

    table.sort(out, function (a, b) return a.name < b.name end);
    return out;
end


Code: Select all
function addClockParams(id, tzs, label, tz)
    indicator.parameters:addString("L" .. id, "Clock " .. id .. " label", "", label);
    indicator.parameters:addString("TZ" .. id, "Clock " .. id .. " timezone", "", tz);
    local i;
    for i = 1, #tzs, 1 do
        indicator.parameters:addStringAlternative("TZ" .. id, tzs[i].name, "", tzs[i].id);
    end
end


Code: Select all
function addClockParams(id, tzs, label, tz)
    indicator.parameters:addString("L" .. id, "Clock " .. id .. " label", "", label);
    indicator.parameters:addString("TZ" .. id, "Clock " .. id .. " timezone", "", tz);
    local i;
    for i = 1, #tzs, 1 do
        indicator.parameters:addStringAlternative("TZ" .. id, tzs[i].name, "", tzs[i].id);
    end
end



Code: Select all
function Prepare(onlyName)


    clockCount = 5;
    for i = 1, 5, 1 do
        clocks[i] = {};
        clocks[i].label = instance.parameters["L" .. i];
        clocks[i].tz = win32.getTimeZone(instance.parameters["TZ" .. i]);
        clocks[i].hour = -1;
        clocks[i].minute = -1;
    end


end

Code: Select all
function AsyncOperationFinished(cookie, success, message)
 
        local time = now();
        local i;

        for i = 1, clockCount, 1 do
            local clock = clocks[i];
            clock.time = win32.convertUTCToTimeZone(clock.tz, time);
            local t = core.dateToTable(clock.time);
            if clock.hour ~= t.hour or
               clock.minute ~= t.min then
                redraw = true;
            end
            clock.hour = t.hour;
            clock.minute = t.min;
            if clockDigital then
                clock.sdate = win32.formatDate(clock.time, win32.SHORT, win32.NONE);
                clock.stime = win32.formatDate(clock.time, win32.NONE, win32.SHORT);
            end
        end
    end
 
end


Code: Select all
function now()
    if __debug__hook ~= nil then
        return core.host:execute("convertTime", core.TZ_EST, core.TZ_UTC, core.now());
    else
        return win32.currentTimeUTC();
    end
end
User avatar
Apprentice
FXCodeBase: Confirmed User
 
Posts: 36341
Joined: Thu Dec 31, 2009 11:59 am
Location: Zagreb, Croatia

Value to Angle

Postby Apprentice » Mon Dec 31, 2012 7:19 am

Code: Select all
function toAngle(value, totalValues)
    return value / totalValues * 2 * math.pi - math.pi / 2;
end
User avatar
Apprentice
FXCodeBase: Confirmed User
 
Posts: 36341
Joined: Thu Dec 31, 2009 11:59 am
Location: Zagreb, Croatia

Output streams synchronized with the specified Stream

Postby Apprentice » Fri Jan 11, 2013 8:51 am

Code: Select all
local buff;

function Prepare(nameOnly)
buff = core.autoBuffer( StreamToSynchronizeTheAutoBufferWidth, first, Shift, BuffUpdateFunctionName, NumberOfStreamsInTheAutoBuffer);
end


function BuffUpdateFunctionName (period)
 if period < first then
 return;
 end
 
 buff.DATA[period] =   Calculate (period);
end

function Update(  period)
   
   buff:update();
   
   if buff.DATA[period] then
   
   end
   
  end
User avatar
Apprentice
FXCodeBase: Confirmed User
 
Posts: 36341
Joined: Thu Dec 31, 2009 11:59 am
Location: Zagreb, Croatia

CancelOrder

Postby Apprentice » Wed Jan 23, 2013 3:37 pm

Code: Select all
function CancelOrder(OrderID)
    local valuemap = core.valuemap();
    valuemap.Command = "DeleteOrder";
    valuemap.OfferID = OfferID;
    valuemap.AcctID = AccountID;
    valuemap.OrderID = OrderID;

    success, message = terminal:execute(102, valuemap);
    if not success then
        terminal:alertMessage(instance.bid:instrument(), instance.bid[instance.bid:size() - 1], "Cancelling order failed:" .. message, instance.bid:date(instance.bid:size() - 1));
    end

end
User avatar
Apprentice
FXCodeBase: Confirmed User
 
Posts: 36341
Joined: Thu Dec 31, 2009 11:59 am
Location: Zagreb, Croatia

CloseTrade

Postby Apprentice » Wed Jan 23, 2013 3:38 pm

Code: Select all
function CloseTrade(TradeID, Amount, Side)
    local valuemap = core.valuemap();

    if Side == "B" then
        Side = "S";
    else
        Side = "B";
    end

    valuemap.Command = "CreateOrder";

    if not CanClose then
        valuemap.OrderType = 'OM'
    else
        valuemap.OrderType = "CM";
    end                         

    valuemap.OfferID = OfferID;
    valuemap.AcctID = AccountID;
    valuemap.Quantity = Amount
    valuemap.BuySell = Side;
    valuemap.TradeID = TradeID;

    success, message = terminal:execute(101, valuemap);
    if not success then
        terminal:alertMessage(instance.bid:instrument(), instance.bid[instance.bid:size() - 1], "Closing trade failed:" .. message, instance.bid:date(instance.bid:size() - 1));
    end
end
User avatar
Apprentice
FXCodeBase: Confirmed User
 
Posts: 36341
Joined: Thu Dec 31, 2009 11:59 am
Location: Zagreb, Croatia

CreateEntry

Postby Apprentice » Wed Jan 23, 2013 3:41 pm

Code: Select all
function CreateEntry(rate, side)
    local valuemap = core.valuemap();

    valuemap.Command = "CreateOrder";
    valuemap.OrderType = "SE";
    valuemap.OfferID = OfferID;
    valuemap.AcctID = AccountID;
    valuemap.Quantity = Amount * LotSize;
    valuemap.Rate = rate;
    valuemap.BuySell = side;
    valuemap.CustomID = CustomID;

    if side == "B" then
        valuemap.PegPriceOffsetPipsLimit = ProfitTarget;
    else
        valuemap.PegPriceOffsetPipsLimit = -ProfitTarget;
    end
    valuemap.PegTypeLimit = "M";

    if not CanClose then
        valuemap.EntryLimitStop = 'Y'
    end

    success, message = terminal:execute(100, valuemap);
    if not success then
        terminal:alertMessage(instance.bid:instrument(), instance.bid[instance.bid:size() - 1], "Creating entry order failed:" .. message, instance.bid:date(instance.bid:size() - 1));
    end
end
User avatar
Apprentice
FXCodeBase: Confirmed User
 
Posts: 36341
Joined: Thu Dec 31, 2009 11:59 am
Location: Zagreb, Croatia

MarketClose

Postby Apprentice » Wed Jan 23, 2013 4:26 pm

Code: Select all
function Init()
strategy.parameters:addString("Trade", "Choose Trade", "", "");
strategy.parameters:setFlag("Trade", core.FLAG_TRADE);
end


Code: Select all
function PrepareTrading()
    AllowMultiple =  instance.parameters.AllowMultiple;
    ALLOWEDSIDE = instance.parameters.ALLOWEDSIDE;

    local PlaySound = instance.parameters.PlaySound;
    if PlaySound then
        SoundFile = instance.parameters.SoundFile;
    else
        SoundFile = nil;
    end
    assert(not(PlaySound) or (PlaySound and SoundFile ~= ""), "Sound file must be chosen");

    ShowAlert = instance.parameters.ShowAlert;
    RecurrentSound = instance.parameters.RecurrentSound;

    SendEmail = instance.parameters.SendEmail;

    if SendEmail then
        Email = instance.parameters.Email;
    else
        Email = nil;
    end
    assert(not(SendEmail) or (SendEmail and Email ~= ""), "E-mail address must be specified");


    AllowTrade = instance.parameters.AllowTrade;   
   AcctID= instance.parameters.AcctID;
    Trade = instance.parameters.Trade;   

end


Code: Select all
function MarketClose(Trade,  ShowAlert, Label, SoundFile,RecurrentSound,Email)

    if not(AllowTrade) then
        return true;
    end

   
     local TradeID = core.host:findTable("trades"):find("TradeID", Trade).TradeID;
   
              if TradeID == nil then
                terminal:alertMessage(instance.bid:instrument(), instance.bid[NOW], "Trade " .. Trade .. " disappear", instance.bid:date(NOW));
                core.host:execute("stop");
                return ;
               end
   
    local AmountK = core.host:findTable("trades"):find("TradeID",  TradeID ).AmountK;
    local Instrument = core.host:findTable("trades"):find("TradeID",  TradeID ).Instrument;       
    local OfferID = core.host:findTable("offers"):find("Instrument",  Instrument ).OfferID; 
    local IsBuy= core.host:findTable("trades"):find("TradeID",  TradeID ).IsBuy;
    local Close= core.host:findTable("trades"):find("TradeID",  TradeID ).Close;
    local lotSize = core.host:execute("getTradingProperty", "baseUnitSize", instance.bid:instrument(), AcctID);
     local CanClose = core.host:execute("getTradingProperty", "canCreateMarketClose", instance.bid:instrument(), AcctID);
   
    if IsBuy then
    Side= "S";
    else
    Side= "B";
    end
   
   
    local valuemap, success, msg;
   
        valuemap = core.valuemap();    
      
      if not CanClose then
         valuemap.OrderType = 'OM'
      else
         valuemap.OrderType = "CM";
      end   
      
      valuemap.Command = "CreateOrder";   
        valuemap.OfferID = OfferID;
      valuemap.Rate = Close;
      valuemap.TradeID = TradeID;
        valuemap.Quantity= AmountK*lotSize;   
        valuemap.AcctID = AcctID;
        valuemap.BuySell = Side;
        success, msg = terminal:execute(200, valuemap);

        if not(success) then         
            terminal:alertMessage(instance.bid:instrument(), instance.bid[instance.bid:size() - 1], "Order failed" .. msg, instance.bid:date(instance.bid:size() - 1));
            return false;
        end
      
      
      
         if ShowAlert then
            terminal:alertMessage(instance.bid:instrument(), instance.bid[NOW],  Label, instance.bid:date(NOW));
         end

         if SoundFile ~= nil then
            terminal:alertSound(SoundFile, RecurrentSound);
         end

         if Email ~= nil then
            terminal:alertEmail(Email, Label, profile:id() .. "(" .. instance.bid:instrument() .. ")" .. instance.bid[NOW]..", " .. Label..", " .. instance.bid:date(NOW));
         end         
         
      
        return true;
        
end


Code: Select all
function ExtAsyncOperationFinished(id, success, message)

    if id == 200  then
   
       if not(success) then
            terminal:alertMessage(instance.bid:instrument() ,  instance.bid[instance.bid:size() - 1], "Position Close Failure" .. message, instance.bid:date(instance.bid:size() - 1));
      else
      core.host:execute("stop");
        end
      
   end
end
User avatar
Apprentice
FXCodeBase: Confirmed User
 
Posts: 36341
Joined: Thu Dec 31, 2009 11:59 am
Location: Zagreb, Croatia

Partial Close

Postby Apprentice » Wed Jan 23, 2013 4:55 pm

Code: Select all

function MarketClose(Trade, Percentage,  ShowAlert, Label, SoundFile,RecurrentSound,Email)

    if not(AllowTrade) then
        return true;
    end

   
     local TradeID = core.host:findTable("trades"):find("TradeID", Trade).TradeID;
   
              if TradeID == nil then
                terminal:alertMessage(instance.bid:instrument(), instance.bid[NOW], "Trade " .. Trade .. " disappear", instance.bid:date(NOW));
                core.host:execute("stop");
                return ;
               end
   
    local AmountK = core.host:findTable("trades"):find("TradeID",  TradeID ).AmountK;
    local Instrument = core.host:findTable("trades"):find("TradeID",  TradeID ).Instrument;       
    local OfferID = core.host:findTable("offers"):find("Instrument",  Instrument ).OfferID; 
    local IsBuy= core.host:findTable("trades"):find("TradeID",  TradeID ).IsBuy;
    local Close= core.host:findTable("trades"):find("TradeID",  TradeID ).Close;
    local lotSize = core.host:execute("getTradingProperty", "baseUnitSize", instance.bid:instrument(), AcctID);
     local CanClose = core.host:execute("getTradingProperty", "canCreateMarketClose", instance.bid:instrument(), AcctID);
   
    if  (( AmountK/100)*Percentage % 1000) ~= 0 then
     terminal:alertMessage(instance.bid:instrument(), instance.bid[instance.bid:size() - 1], "Unable to Execute Partial Close", instance.bid:date(instance.bid:size() - 1));
     core.host:execute("stop");
    return true;   
    end
   
    if IsBuy then
    Side= "S";
    else
    Side= "B";
    end
   
   
    local valuemap, success, msg;
   
        valuemap = core.valuemap();    
      
      if not CanClose then
         valuemap.OrderType = 'OM'
      else
         valuemap.OrderType = "CM";
      end   
      
      valuemap.Command = "CreateOrder";   
        valuemap.OfferID = OfferID;
      valuemap.Rate = Close;
      valuemap.TradeID = TradeID;
      
      if Percentage== 100  then
        valuemap.Quantity= AmountK*lotSize;   
      else
      valuemap.Quantity= (AmountK/100)*Percentage*lotSize;
      end
        valuemap.AcctID = AcctID;
        valuemap.BuySell = Side;
        success, msg = terminal:execute(200, valuemap);

        if not(success) then         
            terminal:alertMessage(instance.bid:instrument(), instance.bid[instance.bid:size() - 1], "Order failed" .. msg, instance.bid:date(instance.bid:size() - 1));
            return false;
        end
      
      
      
         if ShowAlert then
            terminal:alertMessage(instance.bid:instrument(), instance.bid[NOW],  Label, instance.bid:date(NOW));
         end

         if SoundFile ~= nil then
            terminal:alertSound(SoundFile, RecurrentSound);
         end

         if Email ~= nil then
            terminal:alertEmail(Email, Label, profile:id() .. "(" .. instance.bid:instrument() .. ")" .. instance.bid[NOW]..", " .. Label..", " .. instance.bid:date(NOW));
         end         
         
      
        return true;
        
end



Code: Select all
function ExtAsyncOperationFinished(id, success, message)

    if id == 200  then
   
       if not(success) then
            terminal:alertMessage(instance.bid:instrument() ,  instance.bid[instance.bid:size() - 1], "Position Close Failure" .. message, instance.bid:date(instance.bid:size() - 1));
      else
      core.host:execute("stop");
        end
      
   end
end
User avatar
Apprentice
FXCodeBase: Confirmed User
 
Posts: 36341
Joined: Thu Dec 31, 2009 11:59 am
Location: Zagreb, Croatia

LineEquation

Postby Apprentice » Thu Mar 14, 2013 3:46 am

Code: Select all
function GetLineEquationABCK(x1, y1, x2, y2)
   local deltaX, deltaY; 
   local a, b, c, k;     

   deltaX = x2 - x1;                  --  X
   deltaY = y2 - y1;                  --  Y
   a = deltaY;                        -- a
   b = -deltaX;                       -- b
   c = ( y2*deltaX ) - ( x2*deltaY ); -- c
   k = -a / b;               
   
   return a, b, c, k;
end


Code: Select all
[code]
function GetYofABCLine(X, a, b, c)
   return (-a * X - c) / b;
end
--a*x+b*y+c=0[/code]


function intersect(a1, b1, a2, b2)
    local x, y;

    -- collinear
    if a1 == a2 then
        return nil, nil;
    end

    x = (b2 - b1) / (a1 - a2);
    y = a1 * x + b1;
    return x, y;
end

function getline(x1, y1, x2, y2)
    local a, b;

    a = ((y2 - y1) / (x2 - x1));
    b = (y1 - a * x1);
    return a, b;
end

Code: Select all
function Parallel (x,y,  x1 , y1 )

--y = ax +b
-- b=y-ax;
local a = x;
local b = y1-a*x1;

return a, b;

end
User avatar
Apprentice
FXCodeBase: Confirmed User
 
Posts: 36341
Joined: Thu Dec 31, 2009 11:59 am
Location: Zagreb, Croatia

PreviousNext

Return to Indicator Development

Who is online

Users browsing this forum: No registered users and 11 guests