sort core.host:findTable(trades) by Gross P/L

If you need an Indicator or Signal developed or translated from other language, please post all Indicator development REQUESTS to this section here.

Moderator: admin

sort core.host:findTable(trades) by Gross P/L

Postby conjure » Tue Aug 21, 2018 12:34 pm

i have modified a strategy made by Apprentice to feet my needs.

The original strategy is this..

http://fxcodebase.com/code/viewtopic.php?f=31&t=64933&p=113655&hilit=AccountTradeLog#p113655

I have kept some of the code and i manage to output in csv some results, like ...

Balance , Equity , Used Mr , Usable Mr % , Gross P/L
from Accounts table,
and from Trades table,
Symbol ,Amount,S/B, P/L , Gross P/L

the saved csv is loading on my local site, and it is like this shown in the image..

Capture.PNG




What i need to do is to
sort the trades by Gross P/L
BEFORE i save it to csv..




Is it possible?
Can someone help me on that?

Bellow is my modified code..
Code: Select all
-- More information about this indicator can be found at:
-- http://fxcodebase.com/code/viewtopic.php?f=31&t=64933


--+------------------------------------------------------------------+
--|                               Copyright © 2017, Gehtsoft USA LLC |
--|                                            http://fxcodebase.com |
--+------------------------------------------------------------------+
--|                                 Support our efforts by donating  |
--|                                    Paypal: https://goo.gl/9Rj74e |
--|                    BitCoin : 15VCJTLaz12Amr7adHSBtL9v8XomURo9RF  | 
--+------------------------------------------------------------------+
--|                                      Developed by : Mario Jemic  |                   
--|                                          mario.jemic@gmail.com   |
--+------------------------------------------------------------------+

local _gSubscription = {};
local _gUpdatePeriods = {};
local _gLastTime;

local maxTableCount = 5;
function Init() -- The strategy profile initialization
    strategy:name("Account trade Log");
   
    strategy.parameters:addString("Account", "Account", "", "");
    strategy.parameters:setFlag("Account", core.FLAG_ACCOUNT);
   
    local tradesArray={"Instrument","AmountK","BS","PL","GrossPL"};

    GenerateTableSelector("Trades", tradesArray, maxTableCount);

   
    strategy.parameters:addGroup("Log parameters");
    strategy.parameters:addString("File", "File", "", "");
    strategy.parameters:addString("Separator", "separator", "", ",");
    strategy.parameters:addBoolean("IsMerge", "Merge into one file", "", true);     
    strategy.parameters:addString("StartTime", "StartTime", "", "17:00:00");
    strategy.parameters:addString("StopTime", "StopTime", "", "24:00:00");
    strategy.parameters:addInteger("UpdatePeriod", "UpdatePeriod(min)", "", 30, 1, 60);
end
local maxTableCount = 5;
local mAccount;

function GenerateTableSelector(tableName, columnNames, maxTableColumn)
   local column;
    strategy.parameters:addGroup(tableName);
   for column = 1, maxTableColumn do
        GenerateColumnSelector(tableName, columnNames, column)
    end
end

function GenerateColumnSelector(tableName, columnNames, column)

    local columnName = tableName .. "_" .. "Column" .. tostring(column);
   
    local columnIndex = column%#columnNames;
    if columnIndex == 0 then
        columnIndex = 1;
    end
    strategy.parameters:addString(columnName, "Column" .. tostring(column), "", columnNames[columnIndex]);
    for columnAlt = 1, #columnNames do
        strategy.parameters:addStringAlternative(columnName, columnNames[columnAlt], "", columnNames[columnAlt]);
    end
    strategy.parameters:addStringAlternative(columnName, "-", "", "-");
end

local TimerId;
local Logging = nil;
local StartTime = nil;
local StopTime = nil;
local LogAccountsColumns = {};
local LogTradesColumns = {};
local LogClosedTradesColumns = {};
local MergeFileHandle = nil;
local AccountFileHandle = nil;
local TradesFileHandle = nil;
local ClosedTradesFileHandle = nil;
local IsMerge = nil;
local Separator = nil;
local isWriteHeaders = false;

function Prepare(nameOnly)
      mAccount = instance.parameters.Account;
    Account = instance.parameters.Account;
    account = instance.parameters.Account;
 
    local name;
    name = profile:id() .. "( " .. instance.bid:name();
   
   name = name .. ", " .. instance.parameters.File.. ", " .. instance.parameters.StartTime .. ", " .. instance.parameters.StopTime .. ", " .. instance.parameters.UpdatePeriod .. " min"
   
    name = name  ..  " )";
    instance:name(name);
 
    if nameOnly then
        return ;
    end

    assert(instance.parameters.File  ~= "", "Log file not selected, Please select log file ");

    local updatePeriod =  instance.parameters.UpdatePeriod;
    timerId = core.host:execute("setTimer", 100, updatePeriod);

    StartTime, valid = ParseTime(instance.parameters.StartTime);
    assert(valid, "Time " .. instance.parameters.StartTime .. " is invalid");
   
    StopTime, valid = ParseTime(instance.parameters.StopTime);
    assert(valid, "Time " .. instance.parameters.StopTime .. " is invalid");
   
    IsMerge = instance.parameters.IsMerge;
    Separator = instance.parameters.Separator;
     
    LogAccountsColumns = FillLogColumns("Accounts");
    LogTradesColumns = FillLogColumns("Trades");
    LogClosedTradesColumns = FillLogColumns("Closed Trades");

    if IsMerge == true then
    end
   
    Logging = false;
end

function FillLogColumns(tableName)

    local selectedColumns = {};
   for column = 1, maxTableCount do
   
        local id = tableName .. "_" .. "Column" .. tostring(column);     
        local value = instance.parameters:getString(id);
       
        if value == "-" then
            return
        end
       
        selectedColumns[#selectedColumns + 1] = instance.parameters:getString(id);
    end
   
    return selectedColumns;
end

function logMerge(fileHandle, logAccountsColumns, logTradesColumns, logClosedTradesColumns)
---os.remove( instance.parameters.File.. ".csv" )

        fileHandle = io.open(instance.parameters.File.. ".csv", "w");

 
    fileHandle:write("Balance , Equity , Used Mr , Usable Mr % , Gross P/L , ");
    fileHandle:write("\n");

local account = core.host:findTable("accounts"):find("AccountID", Account);
Balance=math.floor(account.Balance)
Equity=math.floor(account.Equity)
Used=math.floor(account.UsedMargin)
Usable=math.floor(getUsableMarginPercent())
Gross=Equity-Balance
Gross=math.floor(Gross)

    fileHandle:write(Balance);
    fileHandle:write(",");
    fileHandle:write(Equity);
    fileHandle:write(",");
    fileHandle:write(Used);
    fileHandle:write(",");
    fileHandle:write(Usable);
   fileHandle:write(",");
    fileHandle:write(Gross);
    fileHandle:write("\n");
       fileHandle:write(Balance);
    fileHandle:write(",");
    fileHandle:write(Equity);
    fileHandle:write(",");
    fileHandle:write(Used);
    fileHandle:write(",");
    fileHandle:write(Usable);
   fileHandle:write(",");
    fileHandle:write(Gross);
    fileHandle:write("\n");
       fileHandle:write("\n");
      
       fileHandle:write("Symbol ,Amount,S/B, P/L , Gross P/L ");
    fileHandle:write("\n");


    logTable(fileHandle, "trades", logTradesColumns)
   
   
   
end

function logTable(fileHandle, tableName, tableColumns)

    for column = 1, #tableColumns do
       --- fileHandle:write(tableColumns[column] .. Separator);
    end;
   
    local enum, row,value;
    enum = core.host:findTable(tableName):enumerator();
    row = enum:next();
    while row ~= nil do
        for column = 1, #tableColumns do
            value = row:cell(tableColumns[column])
            fileHandle:write(tostring(value) .. Separator);
        end
       fileHandle:write("\n")
       row = enum:next();
    end
    ---fileHandle:flush(MergeFileHandle);
         fileHandle:close()

end

function log(logAccountsColumns, logTradesColumns, logClosedTradesColumns)

    local now = core.host:execute("getServerTime");
 

    TradesFileHandle:write(core.formatDate(now));
    TradesFileHandle:write("\n");
    logTable(TradesFileHandle, "trades", logTradesColumns)
   

end

function Update()
    if not(checkReady("trades")) or not(checkReady("orders")) then
        return ;
    end

   local now = core.host:execute("getServerTime");
    -- get only time
    now = now - math.floor(now);
    -- check whether the time is in the exit time period
    if now >= StartTime and now <= StopTime then
        Logging = true; 
    else
        Logging = false;           
    end
end

function AsyncOperationFinished(id, success, msg)
   if id == 100 then
        if Logging == true then
            if IsMerge == true then
                logMerge(MergeFileHandle, LogAccountsColumns, LogTradesColumns, LogClosedTradesColumns);
            else
                log(LogAccountsColumns, LogTradesColumns, LogClosedTradesColumns);
            end
        end
   end
end

function checkReady(table)
    return core.host:execute("isTableFilled", table);
end

function ParseTime(time)
    local Pos = string.find(time, ":");
    local h = tonumber(string.sub(time, 1, Pos - 1));
    time = string.sub(time, Pos + 1);
    Pos = string.find(time, ":");
    local m = tonumber(string.sub(time, 1, Pos - 1));
    local s = tonumber(string.sub(time, Pos + 1));
    return (h / 24.0 +  m / 1440.0 + s / 86400.0),                          -- time in ole format
           ((h >= 0 and h < 24 and m >= 0 and m < 60 and s >= 0 and s < 60) or (h == 24 and m == 0 and s == 0)); -- validity flag
end

local mAccountRow = nil;
local mSummaries = {};

function checkAccountRow()
    if mAccountRow == nil then
        mAccountRow = core.host:findTable("accounts"):find("AccountID", mAccount);
    else
        mAccountRow:refresh();
    end
end


function getUsableMarginPercent()
   checkAccountRow();
   return (mAccountRow.UsableMargin / mAccountRow.Equity) * 100;
end


function getUsableMargin()
    checkAccountRow();
    return mAccountRow.UsableMargin;
end



conjure
FXCodeBase: Initiate
 
Posts: 135
Joined: Sat Jul 22, 2017 7:27 am

Re: sort core.host:findTable(trades) by Gross P/L

Postby Apprentice » Wed Aug 22, 2018 3:18 pm

Your request is added to the development list under Id Number 4236
User avatar
Apprentice
FXCodeBase: Confirmed User
 
Posts: 36341
Joined: Thu Dec 31, 2009 11:59 am
Location: Zagreb, Croatia

Re: sort core.host:findTable(trades) by Gross P/L

Postby Apprentice » Sat Aug 25, 2018 5:22 am

Try this version.
example.lua
(10.02 KiB) Downloaded 461 times
User avatar
Apprentice
FXCodeBase: Confirmed User
 
Posts: 36341
Joined: Thu Dec 31, 2009 11:59 am
Location: Zagreb, Croatia

Re: sort core.host:findTable(trades) by Gross P/L

Postby conjure » Sat Aug 25, 2018 6:15 am

Thank you Apprentice :D !!!
conjure
FXCodeBase: Initiate
 
Posts: 135
Joined: Sat Jul 22, 2017 7:27 am


Return to Indicator and Signal Requests

Who is online

Users browsing this forum: Bing [Bot] and 12 guests