Your order could not be executed

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

Your order could not be executed

Postby conjure » Fri Jun 08, 2018 7:39 am

Hi.
I have made an automated system that opens a position when criteria meets.
though Today i had a problem on Real account.
i ve got a message saying "Your order could not be executed".
so i had to open it manual.

Is there a way to make the strategy trying to reopen the position if an error like this happens again?

Like some code that after executing the command
Code: Select all
if mAllowTrade then createTrueMarketOrder("B", Amount, symbol, stop, false, 50); end

will check if position opened and if not will try to reopen it?
Thank you for your help
conjure
FXCodeBase: Initiate
 
Posts: 135
Joined: Sat Jul 22, 2017 7:27 am

Re: Your order could not be executed

Postby Apprentice » Mon Jun 11, 2018 6:35 am

Can you share your strategy?
So my team can check it out.
User avatar
Apprentice
FXCodeBase: Confirmed User
 
Posts: 36420
Joined: Thu Dec 31, 2009 11:59 am
Location: Zagreb, Croatia

Re: Your order could not be executed

Postby conjure » Mon Jun 11, 2018 8:08 am

Here is my code...

Code: Select all


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

-----------------------------------------------------------
-- Standard strategy init handler for marketscope strategy
-----------------------------------------------------------
function Init()
    strategy:name("System 1 and 2");

   
    strategy:type(core.Both);
   

   
   
   strategy.parameters:addGroup("------------------------------System1 parameters------------------------------");





         strategy.parameters:addDouble("HH3followed3LL", "HH3followed3LL", "", 1);
    strategy.parameters:addDoubleAlternative("HH3followed3LL", "YES", "", 1);
    strategy.parameters:addDoubleAlternative("HH3followed3LL", "NO", "", 0);

        strategy.parameters:addDouble("HH4followed4LL", "HH4followed4LL", "", 1);
    strategy.parameters:addDoubleAlternative("HH4followed4LL", "YES", "", 1);
    strategy.parameters:addDoubleAlternative("HH4followed4LL", "NO", "", 0);

        strategy.parameters:addDouble("HH5followed5LL", "HH5followed5LL", "", 1);
    strategy.parameters:addDoubleAlternative("HH5followed5LL", "YES", "", 1);
    strategy.parameters:addDoubleAlternative("HH5followed5LL", "NO", "", 0);


   
       strategy.parameters:addGroup("ST parameters")
    strategy.parameters:addInteger("ST_N", "Number of periods", "No description", 10);
    strategy.parameters:addDouble("ST_M", "Multiplier", "No description", 1.5);
   
   
      strategy.parameters:addGroup("ADX parameters");
    strategy.parameters:addInteger("ADX_Period", "Period", "", 28);
    strategy.parameters:addDouble("ADX_Level", "Level ADX", "", 25);

   
   
   
   
   strategy.parameters:addGroup("------------------------------General parameters------------------------------");

   
   
    strategy.parameters:addString("Account", "Account", "", "");
    strategy.parameters:setFlag("Account", core.FLAG_ACCOUNT);
       strategy.parameters:addInteger("Amount", "Trade Amount in Lots", "", 1, 1, 10000);

    strategy.parameters:addBoolean("AllowTrade", "Allow trade", "", true);
    strategy.parameters:setFlag("AllowTrade", core.FLAG_ALLOW_TRADE);
    strategy.parameters:addString("AllowedSide", "Allowed side", "Allowed side for trading or signaling, can be Sell, Buy or Both", "Both");
    strategy.parameters:addStringAlternative("AllowedSide", "Both", "", "Both");
    strategy.parameters:addStringAlternative("AllowedSide", "Buy", "", "Buy");
    strategy.parameters:addStringAlternative("AllowedSide", "Sell", "", "Sell");
   
    strategy.parameters:addBoolean("AllowMultiplePositions", "Allow multiple positions", "", false);
    strategy.parameters:addString("tf", "tf_for_HH_LL", "The used timeframe", "H1");
    strategy.parameters:setFlag("tf", core.FLAG_PERIODS);

      strategy.parameters:addGroup("------------------------------TRAILING parameters------------------------------");

   
          strategy.parameters:addString("tf2", "tf2_for TRAILSTOP", "The used timeframe", "m1");
    strategy.parameters:setFlag("tf2", core.FLAG_PERIODS);
   
   
   
               strategy.parameters:addGroup("TRAILSTOP parameters");
       strategy.parameters:addDouble("PLAYLIMIT", "TRAILSTOP", "", 1);
    strategy.parameters:addDoubleAlternative("PLAYLIMIT", "YES", "", 1);
    strategy.parameters:addDoubleAlternative("PLAYLIMIT", "NO", "", 0);
    strategy.parameters:addDouble("limit", " over how much should start  the TRAILSTOP", "", 1000);
          strategy.parameters:addDouble("stop8", "stop", "", -1000);

          strategy.parameters:addDouble("dieresi", "dieresi", "", 2);

      
             strategy.parameters:addInteger("stop", "Stop Order in pips", "", 100, 1, 10000);

      
      
      

end

local HH3followed3LL;
local HH4followed4LL;
local HH5followed5LL;
local PLAYLIMIT;


local mCID= "FXSW_STRATEGY";
local mAccount;
local mLotSize;
local mAllowTrade = false;
local Amount;


local ST_N;
local ST_M;
local ST;
local ADX_Level,ADX_Period;

local mAllowedSide = "Both";
local mPlaySound = false;
local mReccurentSound = false;
local mSendEmail = false;
local mShowAlert = false;

local mEmail;
local mAllowMultiplePositions = true;

local tf;
local tf2;


local symbol;

local stop;


local source;
local id_source = 101;

local source2;
local id_source2 = 102;



local stop8;
local limit;
local dieresi;

-----------------------------------------------------------
-- Standard prepare handler for marketscope strategy
-----------------------------------------------------------
function Prepare(onlyName)
    assert(instance.parameters.tf ~= "t1", "Tick is not allowed for tf parameter");

        HH3followed3LL = instance.parameters.HH3followed3LL;
        HH4followed4LL = instance.parameters.HH4followed4LL;
        HH5followed5LL = instance.parameters.HH5followed5LL;
    PLAYLIMIT = instance.parameters.PLAYLIMIT;
    stop = instance.parameters.stop;
   

    -- collect parameters
   symbol = instance.bid:instrument();
    mAccount = instance.parameters.Account;
    mLotSize = core.host:execute("getTradingProperty", "baseUnitSize", instance.bid:instrument(), mAccount);
    mAllowTrade = instance.parameters.AllowTrade;
    mAllowedSide = instance.parameters.AllowedSide;
       Amount = instance.parameters.Amount;


   
    mAllowMultiplePositions = instance.parameters.AllowMultiplePositions;
   mShowAlert = instance.parameters.SHOWALERT;

   
   
    tf = instance.parameters.tf;
    tf2 = instance.parameters.tf2;

   
   stop8 = instance.parameters.stop8;
    limit = instance.parameters.limit;
   dieresi = instance.parameters.dieresi;
   
   
   
       N = instance.parameters.SUPERTREND_N;
    M = instance.parameters.SUPERTREND_M;
      ADX_Period= instance.parameters.ADX_Period;   
   ADX_Level= instance.parameters.ADX_Level;

   
   
   
    --set name
    instance:name(profile:id() .. "(" .. instance.bid:instrument()  .. "(" .. tf  .. "))");
   
    if onlyName then
        return;
    end

   
    --datasources 
   
    source = ExtSubscribe(id_source, symbol, tf, true, "bar");
    source2 = ExtSubscribe(id_source2, symbol, tf2, true, "bar");

   
   
    --indicators
       ST = core.indicators:create("ST", source, N,M,  core.rgb(0, 255, 0),  core.rgb(255, 0, 0)  );
     ADX = core.indicators:create("ADX", source, ADX_Period  );
    _gUpdatePeriods[ADX.DATA] = _gUpdatePeriods[source];

end

-----------------------------------------------------------
-- 'Event handler' that is called when a datasource is updated
-----------------------------------------------------------




function ExtUpdate(id, updatedSource, period)
    if not checkReady("trades") or not checkReady("summary") then
        return;
    end
   


   
   
   
           -- update indicators values
    ST:update(core.UpdateLast);
    ADX:update(core.UpdateLast);


   
    -- update expressions
    -- processing of Activation points
    if id==id_source then --Updates handler of 'source' datasource ('tf'  timeframe)


   if HH5followed5LL >0 then
if source.close[ period] > source.close[ period-1]
and source.high[ period] > source.high[ period-1]
and source.close[ period-1] > source.close[ period-2]
and source.high[ period-1] > source.high[ period-2]
and source.close[ period-2] > source.close[ period-3]
and source.high[ period-2] > source.high[ period-3]
and source.close[ period-3] > source.close[ period-4]
and source.high[ period-3] > source.high[ period-4]
and source.close[ period-4] > source.close[ period-5]
and source.high[ period-4] > source.high[ period-5]



and source.close[ period-5] < source.close[ period-6]
and source.low[ period-5] < source.low[ period-6]
and source.close[ period-6] < source.close[ period-7]
and source.low[ period-6] < source.low[ period-7]
and source.close[ period-7] < source.close[ period-8]
and source.low[ period-7] < source.low[ period-8]
and source.close[ period-8] < source.close[ period-9]
and source.low[ period-8] < source.low[ period-9]
and source.close[ period-9] < source.close[ period-10]
and source.low[ period-9] < source.low[ period-10]
      and ST.DATA:colorI(period) ==  core.rgb(0, 255, 0)
      and ADX.DATA[ period]> ADX_Level


then

               if mAllowTrade then createTrueMarketOrder("B", Amount, symbol, stop, false, 50); end
                if mAllowTrade then  close("S", core.host:findTable("offers"):find("Instrument", symbol).OfferID); end

      end

      
if source.close[ period] < source.close[ period-1]
and source.high[ period] < source.high[ period-1]
and source.close[ period-1] < source.close[ period-2]
and source.high[ period-1] < source.high[ period-2]
and source.close[ period-2] < source.close[ period-3]
and source.high[ period-2] < source.high[ period-3]
and source.close[ period-3] < source.close[ period-4]
and source.high[ period-3] < source.high[ period-4]
and source.close[ period-4] < source.close[ period-5]
and source.high[ period-4] < source.high[ period-5]



and source.close[ period-5] > source.close[ period-6]
and source.low[ period-5] > source.low[ period-6]
and source.close[ period-6] > source.close[ period-7]
and source.low[ period-6] > source.low[ period-7]
and source.close[ period-7] > source.close[ period-8]
and source.low[ period-7] > source.low[ period-8]
and source.close[ period-8] > source.close[ period-9]
and source.low[ period-8] > source.low[ period-9]
and source.close[ period-9] > source.close[ period-10]
and source.low[ period-9] > source.low[ period-10]
      and ST.DATA:colorI(period) ==  core.rgb(255, 0, 0)
      and ADX.DATA[ period]> ADX_Level

then

               if mAllowTrade then createTrueMarketOrder("S", Amount, symbol, stop, false, 50); end
                if mAllowTrade then  close("B", core.host:findTable("offers"):find("Instrument", symbol).OfferID); end

      end

end


   if HH4followed4LL >0 then
if source.close[ period] > source.close[ period-1]
and source.high[ period] > source.high[ period-1]
and source.close[ period-1] > source.close[ period-2]
and source.high[ period-1] > source.high[ period-2]
and source.close[ period-2] > source.close[ period-3]
and source.high[ period-2] > source.high[ period-3]
and source.close[ period-3] > source.close[ period-4]
and source.high[ period-3] > source.high[ period-4]



and source.close[ period-4] < source.close[ period-5]
and source.low[ period-4] < source.low[ period-5]
and source.close[ period-5] < source.close[ period-6]
and source.low[ period-5] < source.low[ period-6]
and source.close[ period-6] < source.close[ period-7]
and source.low[ period-6] < source.low[ period-7]
and source.close[ period-7] < source.close[ period-8]
and source.low[ period-7] < source.low[ period-8]
      and ST.DATA:colorI(period) ==  core.rgb(0, 255, 0)
      and ADX.DATA[ period]> ADX_Level


then

               if mAllowTrade then createTrueMarketOrder("B", Amount, symbol, stop, false, 50); end
                if mAllowTrade then  close("S", core.host:findTable("offers"):find("Instrument", symbol).OfferID); end

      end

      
if source.close[ period] < source.close[ period-1]
and source.high[ period] < source.high[ period-1]
and source.close[ period-1] < source.close[ period-2]
and source.high[ period-1] < source.high[ period-2]
and source.close[ period-2] < source.close[ period-3]
and source.high[ period-2] < source.high[ period-3]
and source.close[ period-3] < source.close[ period-4]
and source.high[ period-3] < source.high[ period-4]



and source.close[ period-4] > source.close[ period-5]
and source.low[ period-4] > source.low[ period-5]
and source.close[ period-5] > source.close[ period-6]
and source.low[ period-5] > source.low[ period-6]
and source.close[ period-6] > source.close[ period-7]
and source.low[ period-6] > source.low[ period-7]
and source.close[ period-7] > source.close[ period-8]
and source.low[ period-7] > source.low[ period-8]
      and ST.DATA:colorI(period) ==  core.rgb(255, 0, 0)
      and ADX.DATA[ period]> ADX_Level

then

               if mAllowTrade then createTrueMarketOrder("S", Amount, symbol, stop, false, 50); end
                if mAllowTrade then  close("B", core.host:findTable("offers"):find("Instrument", symbol).OfferID); end

      end

end


   if HH3followed3LL >0 then
if source.close[ period] > source.close[ period-1]
and source.high[ period] > source.high[ period-1]
and source.close[ period-1] > source.close[ period-2]
and source.high[ period-1] > source.high[ period-2]
and source.close[ period-2] > source.close[ period-3]
and source.high[ period-2] > source.high[ period-3]



and source.close[ period-3] < source.close[ period-4]
and source.low[ period-3] < source.low[ period-4]
and source.close[ period-4] < source.close[ period-5]
and source.low[ period-4] < source.low[ period-5]
and source.close[ period-5] < source.close[ period-6]
and source.low[ period-5] < source.low[ period-6]
      and ST.DATA:colorI(period) ==  core.rgb(0, 255, 0)
      and ADX.DATA[ period]> ADX_Level


then

               if mAllowTrade then createTrueMarketOrder("B", Amount, symbol, stop, false, 50); end
                if mAllowTrade then  close("S", core.host:findTable("offers"):find("Instrument", symbol).OfferID); end

      end

      
if source.close[ period] < source.close[ period-1]
and source.high[ period] < source.high[ period-1]
and source.close[ period-1] < source.close[ period-2]
and source.high[ period-1] < source.high[ period-2]
and source.close[ period-2] < source.close[ period-3]
and source.high[ period-2] < source.high[ period-3]



and source.close[ period-3] > source.close[ period-4]
and source.low[ period-3] > source.low[ period-4]
and source.close[ period-4] > source.close[ period-5]
and source.low[ period-4] > source.low[ period-5]
and source.close[ period-5] > source.close[ period-6]
and source.low[ period-5] > source.low[ period-6]
      and ST.DATA:colorI(period) ==  core.rgb(255, 0, 0)
      and ADX.DATA[ period]> ADX_Level

then

               if mAllowTrade then createTrueMarketOrder("S", Amount, symbol, stop, false, 50); end
                if mAllowTrade then  close("B", core.host:findTable("offers"):find("Instrument", symbol).OfferID); end

      end

end










   
   
end


   
       if id==id_source2 then --Updates handler of 'source' datasource ('tf'  timeframe)

         if PLAYLIMIT>0 then

if getGrossPL(symbol) > limit then stop7 = getGrossPL(symbol)/dieresi  if stop7>stop8 then stop8=stop7 end end
if getGrossPL(symbol) < stop8 then
                if mAllowTrade then  close("B", core.host:findTable("offers"):find("Instrument", symbol).OfferID); end
                if mAllowTrade then  close("S", core.host:findTable("offers"):find("Instrument", symbol).OfferID); end
    stop8 = instance.parameters.stop8;
    limit = instance.parameters.limit;

   end



   end

   
   end
   
   
   
   










end









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

-----------------------------------------------------------
--Enters to the market
--   side: B - BUY or S - SELL
--   amount: order amount
--   instrumentName: instrument of order
--   stop:  0, 1 or greater value
--   isTrailingStop: true/false
--   limit: 0, 1 or greater value
-----------------------------------------------------------
function createTrueMarketOrder(side, amount, instrumentName, stop, isTrailingStop, limit)
    if not mAllowTrade then
        return;
    end
   
    local offerId = core.host:findTable("offers"):find("Instrument", instrumentName).OfferID;     
   
    if not (mAllowedSide == "Both" or (mAllowedSide == "Buy" and side == "B") or (mAllowedSide == "Sell" and side == "S")) then
        return;
    end
   
    if not mAllowMultiplePositions then
       if (side == 'B' and countLongPositions(instrumentName) > 0) then
           return;
       elseif (side == 'S' and countShortPositions(instrumentName) > 0) then
           return;
       end
    end
   
   
    local valuemap;
   
    valuemap = core.valuemap();
    valuemap.Command = "CreateOrder";
    valuemap.OrderType = "OM";
    valuemap.OfferID = offerId;
    valuemap.AcctID = mAccount;
    valuemap.GTC = "FOK"; --Fill or Kill order to avoid partial execution
    valuemap.Quantity = amount * mLotSize;
    valuemap.BuySell = side;
    valuemap.CustomID = mCID;
    if stop >= 1 then
        valuemap.PegTypeStop = "M";
        if side == "B" then
            valuemap.PegPriceOffsetPipsStop = - stop;
        else
            valuemap.PegPriceOffsetPipsStop = stop;
        end
        if isTrailingStop then
           valuemap.TrailStepStop = 1;
        end
    end
    if limit >= 1 then
        valuemap.PegTypeLimit = "M";
        if side == "B" then
            valuemap.PegPriceOffsetPipsLimit = limit;
        else
            valuemap.PegPriceOffsetPipsLimit = -limit;
        end
    end

    if (not canClose(instrumentName)) and (stop >= 1 or limit >= 1) then
        valuemap.EntryLimitStop = 'Y'
    end
   
    success, msg = terminal:execute(200, valuemap);
    assert(success, msg);
end



-----------------------------------------------------------
-- closes all positions of the specified direction (B for buy, S for sell)
-----------------------------------------------------------
function canClose(instrumentName)
    return core.host:execute("getTradingProperty", "canCreateMarketClose", instrumentName, mAccount);
end

function close(side, offer)
    local enum, row, valuemap;

    enum = core.host:findTable("trades"):enumerator();
    while true do
        row = enum:next();
        if row == nil then
            break;
        end
        if row.AccountID == mAccount and
           row.OfferID == offer and
           row.BS == side and
           row.QTXT == mCID then
            -- if trade has to be closed

            if canClose(row.Instrument) then
                -- create a close market order when hedging is allowed
                valuemap = core.valuemap();
                valuemap.OrderType = "CM";
                valuemap.OfferID = offer;
                valuemap.AcctID = mAccount;
                valuemap.Quantity = row.Lot;
                valuemap.TradeID = row.TradeID;
                valuemap.CustomID = mCID;
                if row.BS == "B" then
                    valuemap.BuySell = "S";
                else
                    valuemap.BuySell = "B";
                end
                success, msg = terminal:execute(200, valuemap);
                assert(success, msg);
            else               
                -- create an opposite market order when FIFO
                valuemap = core.valuemap();
                valuemap.OrderType = "OM";
                valuemap.OfferID = offer;
                valuemap.AcctID = mAccount;
                valuemap.Quantity = row.Lot;
                valuemap.CustomID = mCID;
                if row.BS == "B" then
                    valuemap.BuySell = "S";
                else
                    valuemap.BuySell = "B";
                end
                success, msg = terminal:execute(200, valuemap);
                assert(success, msg);
            end
        end
    end
end

-----------------------------------------------------------
--Handle command execution result
-----------------------------------------------------------
function ExtAsyncOperationFinished(cookie, success, message)
    if cookie == 1 then
        loaded = true;
    elseif cookie == 200 then
        assert(success, message);
    end
   
end

-----------------------------------------------------------
-- Helper functions
-----------------------------------------------------------
function getOppositeSide(side)
    if(side == "B") then
        return "S";
    else
        return "B";
    end
end

function getDSPeriod(ds, updatedSource, period)
    local p;
    if ds:isBar() then
        p = core.findDate(ds.open, updatedSource:date(period), false);
    else
        p = core.findDate(ds, updatedSource:date(period), false);
    end
    if (p > ds:size() - 1) then
        p = ds:size() - 1;
    elseif (p < ds:first()) then
        p = ds:first();
    end
    return p;
end


-----------------------------------------------------------
-- Allow to calculate last closed bar period for ds datasource
-- which has not tick frequency updates
-----------------------------------------------------------
function getClosedPeriod(ds, supposedPeriod)
    --Check if datasource lastdate is closed on updatePeriod or shift supposedPeriod to -1
    if _gUpdatePeriods[ds] == 't1' or _gUpdatePeriods[ds] == nil then
        return supposedPeriod;
    else
        return supposedPeriod - 1;
    end
end

-----------------------------------------------------------
--Helper functions to wrap the table's method call into the simple function call
-----------------------------------------------------------
function streamSize(stream)
    return stream:size();
end

function streamHasData(stream, period)
    return stream:hasData(period);
end

function canCalculate(stream, period)
    return (period >= 0) and (period > stream:first()) and streamHasData(stream, period);
end

-----------------------------------------------------------
-- Helper functions to be sure that you work with a tick stream
-----------------------------------------------------------
function getTickStreamOfPriceType(stream, priceType)
    if stream:isBar() then
        if priceType == "open" then
            return stream.open;
        elseif priceType == "high" then
            return stream.high;   
        elseif priceType == "low" then
            return stream.low;
        elseif priceType == "close" then
            return stream.close;
        elseif priceType == "typical" then
            return stream.typical;
        elseif priceType == "weighted" then
            return stream.weighted;
        elseif priceType == "volume" then
            return stream.volume;
        else
            return stream.close;
        end
    else
       return stream;
    end
end

function selectStream(safeStream, subStream)
    if safeStream:isBar() then
       return subStream;
    else
       return safeStream;
    end
end

---------------------------------------------------------
-- Subscription for updates by datasource timeframe
---------------------------------------------------------

-- subscribe for the price data
function ExtSubscribe(id, instrument, period, bid, type)
    local sub = {};
    if instrument == nil and period == "t1" then
        if bid then
            sub.stream = instance.bid;
        else
            sub.stream = instance.ask;
        end
        sub.tick = true;
        sub.loaded = true;
        sub.lastSerial = -1;
        _gSubscription[id] = sub;
    elseif instrument == nil then
        sub.stream = core.host:execute("getHistory", id, instance.bid:instrument(), period, 0, 0, bid);
        sub.tick = false;
        sub.loaded = false;
        sub.lastSerial = -1;
        _gSubscription[id] = sub;
    else
        sub.stream = core.host:execute("getHistory", id, instrument, period, 0, 0, bid);
        sub.tick = (period == "t1");
        sub.loaded = false;
        sub.lastSerial = -1;
        _gSubscription[id] = sub;
    end
    _gUpdatePeriods[sub.stream] = period;
    if sub.tick then
        return sub.stream;
    else
        if type == "open" then
            _gUpdatePeriods[sub.stream.open] = period;
            return sub.stream.open;
        elseif type == "high" then
            _gUpdatePeriods[sub.stream.high] = period;
            return sub.stream.high;
        elseif type == "low" then
            _gUpdatePeriods[sub.stream.low] = period;
            return sub.stream.low;
        elseif type == "close" then
            _gUpdatePeriods[sub.stream.close] = period;
            return sub.stream.close;
        elseif type == "bar" then
            _gUpdatePeriods[sub.stream.open] = period;
            _gUpdatePeriods[sub.stream.high] = period;
            _gUpdatePeriods[sub.stream.low] = period;
            _gUpdatePeriods[sub.stream.close] = period;
            _gUpdatePeriods[sub.stream.median] = period;
            _gUpdatePeriods[sub.stream.typical] = period;
            _gUpdatePeriods[sub.stream.volume] = period;
            _gUpdatePeriods[sub.stream.weighted] = period;
            return sub.stream;
        else
            assert(false, type .. " is unknown");
        end
    end
end

function AsyncOperationFinished(cookie, success, message)
    local sub;
    sub = _gSubscription[cookie];
    if sub ~= nil then
        sub.loaded = true;
        if sub.stream:size() > 1 then
           sub.lastSerial = sub.stream:serial(sub.stream:size() - 1);
        end
    else
        -- unknown cookie
        if ExtAsyncOperationFinished ~= nil then
            ExtAsyncOperationFinished(cookie, success, message)
        end
    end
end

function Update()
    if instance.bid:size() > 0 then
        _gLastTime = instance.bid:date(instance.bid:size() - 1);
    end
    for k, v in pairs(_gSubscription) do
        if v.loaded and v.stream:size() > 1 then
            local s = v.stream:serial(v.stream:size() - 1);
            local p;
            if s ~= v.lastSerial then
                if v.tick then
                    p = v.stream:size() - 1;    -- the last tick
                else
                    p = v.stream:size() - 2;    -- the previous candle
                end
                ExtUpdate(k, v.stream, p);
                v.lastSerial = s;
            end
        end
    end
end

---------------------------------------------------------
-- Additional functions
---------------------------------------------------------
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 checkSummaryRow(sInstrument)
    local sOfferID, summaryIter, summaryRow;
   
    if mSummaries[sInstrument] ~= nil then
        --try refresh
        if not (mSummaries[sInstrument]:refresh()) then
            mSummaries[sInstrument] = nil;
        end
    end
   
    --re-read all cache
    if mSummaries[sInstrument] == nil then
        sOfferID = core.host:findTable("offers"):find("Instrument", sInstrument).OfferID;
        summaryIter = core.host:findTable("summary"):enumerator();
        summaryRow = summaryIter:next();
        while summaryRow ~= nil do
            if summaryRow.OfferID == sOfferID then
                mSummaries[sInstrument] = summaryRow;
                break;
            end
            summaryRow = summaryIter:next();
        end
    end
end

function getEquity()
   
    checkAccountRow();
    return mAccountRow.Equity;
end

function getBalance()
    checkAccountRow();
    return mAccountRow.Balance;
end

function getProfit()
    checkAccountRow();
    return mAccountRow.Equity - mAccountRow.Balance;
end

function getAmountK(sInstrument)
    local res;
    checkSummaryRow(sInstrument);
    res = mSummaries[sInstrument];
    if res == nil then
        return 0;
    else
        return res.AmountK;
    end
end

function getGrossPL(sInstrument)
    local res;
    checkSummaryRow(sInstrument);
    res = mSummaries[sInstrument];
    if res == nil then
        return 0;
    else
        return res.GrossPL;
    end
end

function getNetPL(sInstrument)
    local res;
    checkSummaryRow(sInstrument);
    res = mSummaries[sInstrument];
    if res == nil then
        return 0;
    else
        return res.NetPL;
    end
end

function getSellAmountK(sInstrument)
    local res;
    checkSummaryRow(sInstrument);
    res = mSummaries[sInstrument];
    if res == nil then
        return 0;
    else
        return res.SellAmountK;
    end
end

function getBuyAmountK(sInstrument)
    local res;
    checkSummaryRow(sInstrument);
    res = mSummaries[sInstrument];
    if res == nil then
        return 0;
    else
        return res.BuyAmountK;
    end
end

function getBuyNetPLPip(sInstrument)
    local res;
    checkSummaryRow(sInstrument);
    res = mSummaries[sInstrument];
    if res == nil then
        return 0;
    else
        return res.BuyNetPLPip;
    end
end

function getSellNetPLPip(sInstrument)
    local res;
    checkSummaryRow(sInstrument);
    res = mSummaries[sInstrument];
    if res == nil then
        return 0;
    else
        return res.SellNetPLPip;
    end
end

function getBuyNetPL(sInstrument)
    local res;
    checkSummaryRow(sInstrument);
    res = mSummaries[sInstrument];
    if res == nil then
        return 0;
    else
        return res.BuyNetPL;
    end
end

function getSellNetPL(sInstrument)
    local res;
    checkSummaryRow(sInstrument);
    res = mSummaries[sInstrument];
    if res == nil then
        return 0;
    else
        return res.SellNetPL;
    end
end


function countPositions(sInstrument)
    local tradesIter, tradeRow, count, sOfferID;
    count = 0;
    if sInstrument ~= nil then
        sOfferID = core.host:findTable("offers"):find("Instrument", sInstrument).OfferID;
    end
    tradesIter = core.host:findTable("trades"):enumerator();
    tradeRow = tradesIter:next();
    while tradeRow ~= nil do
        if (sInstrument == nil or tradeRow.OfferID == sOfferID) then
            count = count + 1;
        end
        tradeRow = tradesIter:next();
    end
    return count;
end

function countLongPositions(sInstrument)
    local tradesIter, tradeRow, count, sOfferID;
    count = 0;
    if sInstrument ~= nil then
        sOfferID = core.host:findTable("offers"):find("Instrument", sInstrument).OfferID;
    end
    tradesIter = core.host:findTable("trades"):enumerator();
    tradeRow = tradesIter:next();
    while tradeRow ~= nil do
        if ((sInstrument==nil or tradeRow.OfferID == sOfferID) and tradeRow.BS == "B") then
            count = count + 1;
        end
        tradeRow = tradesIter:next();
    end
    return count;
end

function countShortPositions(sInstrument)
    local tradesIter, tradeRow, count, sOfferID;
    count = 0;
    if sInstrument ~= nil then
        sOfferID = core.host:findTable("offers"):find("Instrument", sInstrument).OfferID;
    end
    tradesIter = core.host:findTable("trades"):enumerator();
    tradeRow = tradesIter:next();
    while tradeRow ~= nil do
        if ((sInstrument == nil or tradeRow.OfferID == sOfferID) and tradeRow.BS == "S") then
            count = count + 1;
        end
        tradeRow = tradesIter:next();
    end
    return count;
end

function getLastUpdateTime()
    if (_gLastTime == nil) then
        return 0;
    else
        return _gLastTime;
    end
end

function time(hours, minutes, seconds)
    local dtLast;
    dtLast = core.dateToTable(_gLastTime);
    if seconds == nil then
        seconds = 0;
    end
    return core.datetime(dtLast.year, dtLast.month, dtLast.day, hours, minutes, seconds);
end

function isValidDate(checkDate)
   if (checkDate < 1) then
       return false;
   else
       return true;
   end
end

function parseTime(sTime)
    local iDelimHMPos = string.find(sTime, ":");
    local h = tonumber(string.sub(sTime, 1, iDelimHMPos - 1));
    local sTimeTile = string.sub(sTime, iDelimHMPos + 1);
    local iDelimMSPos = string.find(sTimeTile, ":");
    local m, s;
    s = 0;
    if iDelimMSPos == nil then
        m = tonumber(sTimeTile);
    else
        m = tonumber(string.sub(sTimeTile, 1, iDelimMSPos - 1));
        s = tonumber(string.sub(sTimeTile, iDelimMSPos + 1));
    end
    return time(h, m, s);
end

function getPipSize(sInstrument)
    return core.host:findTable("offers"):find("Instrument", sInstrument).PointSize;
end






What i need is that:
If the order failed to execute ,
to try to reopen the position
in the range of 10 pips.

If there is a slippage bigger of 10 pips from the price it tried to open the position ,
then it should stop trying to open it..
Is that possible?
conjure
FXCodeBase: Initiate
 
Posts: 135
Joined: Sat Jul 22, 2017 7:27 am

Re: Your order could not be executed

Postby Apprentice » Mon Jun 11, 2018 11:47 am

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

Re: Your order could not be executed

Postby Victor.Tereschenko » Tue Jun 12, 2018 5:56 am

conjure wrote:Here is my code...

Code: Select all


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

-----------------------------------------------------------
-- Standard strategy init handler for marketscope strategy
-----------------------------------------------------------
function Init()
    strategy:name("System 1 and 2");

   
    strategy:type(core.Both);
   

   
   
   strategy.parameters:addGroup("------------------------------System1 parameters------------------------------");





         strategy.parameters:addDouble("HH3followed3LL", "HH3followed3LL", "", 1);
    strategy.parameters:addDoubleAlternative("HH3followed3LL", "YES", "", 1);
    strategy.parameters:addDoubleAlternative("HH3followed3LL", "NO", "", 0);

        strategy.parameters:addDouble("HH4followed4LL", "HH4followed4LL", "", 1);
    strategy.parameters:addDoubleAlternative("HH4followed4LL", "YES", "", 1);
    strategy.parameters:addDoubleAlternative("HH4followed4LL", "NO", "", 0);

        strategy.parameters:addDouble("HH5followed5LL", "HH5followed5LL", "", 1);
    strategy.parameters:addDoubleAlternative("HH5followed5LL", "YES", "", 1);
    strategy.parameters:addDoubleAlternative("HH5followed5LL", "NO", "", 0);


   
       strategy.parameters:addGroup("ST parameters")
    strategy.parameters:addInteger("ST_N", "Number of periods", "No description", 10);
    strategy.parameters:addDouble("ST_M", "Multiplier", "No description", 1.5);
   
   
      strategy.parameters:addGroup("ADX parameters");
    strategy.parameters:addInteger("ADX_Period", "Period", "", 28);
    strategy.parameters:addDouble("ADX_Level", "Level ADX", "", 25);

   
   
   
   
   strategy.parameters:addGroup("------------------------------General parameters------------------------------");

   
   
    strategy.parameters:addString("Account", "Account", "", "");
    strategy.parameters:setFlag("Account", core.FLAG_ACCOUNT);
       strategy.parameters:addInteger("Amount", "Trade Amount in Lots", "", 1, 1, 10000);

    strategy.parameters:addBoolean("AllowTrade", "Allow trade", "", true);
    strategy.parameters:setFlag("AllowTrade", core.FLAG_ALLOW_TRADE);
    strategy.parameters:addString("AllowedSide", "Allowed side", "Allowed side for trading or signaling, can be Sell, Buy or Both", "Both");
    strategy.parameters:addStringAlternative("AllowedSide", "Both", "", "Both");
    strategy.parameters:addStringAlternative("AllowedSide", "Buy", "", "Buy");
    strategy.parameters:addStringAlternative("AllowedSide", "Sell", "", "Sell");
   
    strategy.parameters:addBoolean("AllowMultiplePositions", "Allow multiple positions", "", false);
    strategy.parameters:addString("tf", "tf_for_HH_LL", "The used timeframe", "H1");
    strategy.parameters:setFlag("tf", core.FLAG_PERIODS);

      strategy.parameters:addGroup("------------------------------TRAILING parameters------------------------------");

   
          strategy.parameters:addString("tf2", "tf2_for TRAILSTOP", "The used timeframe", "m1");
    strategy.parameters:setFlag("tf2", core.FLAG_PERIODS);
   
   
   
               strategy.parameters:addGroup("TRAILSTOP parameters");
       strategy.parameters:addDouble("PLAYLIMIT", "TRAILSTOP", "", 1);
    strategy.parameters:addDoubleAlternative("PLAYLIMIT", "YES", "", 1);
    strategy.parameters:addDoubleAlternative("PLAYLIMIT", "NO", "", 0);
    strategy.parameters:addDouble("limit", " over how much should start  the TRAILSTOP", "", 1000);
          strategy.parameters:addDouble("stop8", "stop", "", -1000);

          strategy.parameters:addDouble("dieresi", "dieresi", "", 2);

      
             strategy.parameters:addInteger("stop", "Stop Order in pips", "", 100, 1, 10000);

      
      
      

end

local HH3followed3LL;
local HH4followed4LL;
local HH5followed5LL;
local PLAYLIMIT;


local mCID= "FXSW_STRATEGY";
local mAccount;
local mLotSize;
local mAllowTrade = false;
local Amount;


local ST_N;
local ST_M;
local ST;
local ADX_Level,ADX_Period;

local mAllowedSide = "Both";
local mPlaySound = false;
local mReccurentSound = false;
local mSendEmail = false;
local mShowAlert = false;

local mEmail;
local mAllowMultiplePositions = true;

local tf;
local tf2;


local symbol;

local stop;


local source;
local id_source = 101;

local source2;
local id_source2 = 102;



local stop8;
local limit;
local dieresi;

-----------------------------------------------------------
-- Standard prepare handler for marketscope strategy
-----------------------------------------------------------
function Prepare(onlyName)
    assert(instance.parameters.tf ~= "t1", "Tick is not allowed for tf parameter");

        HH3followed3LL = instance.parameters.HH3followed3LL;
        HH4followed4LL = instance.parameters.HH4followed4LL;
        HH5followed5LL = instance.parameters.HH5followed5LL;
    PLAYLIMIT = instance.parameters.PLAYLIMIT;
    stop = instance.parameters.stop;
   

    -- collect parameters
   symbol = instance.bid:instrument();
    mAccount = instance.parameters.Account;
    mLotSize = core.host:execute("getTradingProperty", "baseUnitSize", instance.bid:instrument(), mAccount);
    mAllowTrade = instance.parameters.AllowTrade;
    mAllowedSide = instance.parameters.AllowedSide;
       Amount = instance.parameters.Amount;


   
    mAllowMultiplePositions = instance.parameters.AllowMultiplePositions;
   mShowAlert = instance.parameters.SHOWALERT;

   
   
    tf = instance.parameters.tf;
    tf2 = instance.parameters.tf2;

   
   stop8 = instance.parameters.stop8;
    limit = instance.parameters.limit;
   dieresi = instance.parameters.dieresi;
   
   
   
       N = instance.parameters.SUPERTREND_N;
    M = instance.parameters.SUPERTREND_M;
      ADX_Period= instance.parameters.ADX_Period;   
   ADX_Level= instance.parameters.ADX_Level;

   
   
   
    --set name
    instance:name(profile:id() .. "(" .. instance.bid:instrument()  .. "(" .. tf  .. "))");
   
    if onlyName then
        return;
    end

   
    --datasources 
   
    source = ExtSubscribe(id_source, symbol, tf, true, "bar");
    source2 = ExtSubscribe(id_source2, symbol, tf2, true, "bar");

   
   
    --indicators
       ST = core.indicators:create("ST", source, N,M,  core.rgb(0, 255, 0),  core.rgb(255, 0, 0)  );
     ADX = core.indicators:create("ADX", source, ADX_Period  );
    _gUpdatePeriods[ADX.DATA] = _gUpdatePeriods[source];

end

-----------------------------------------------------------
-- 'Event handler' that is called when a datasource is updated
-----------------------------------------------------------




function ExtUpdate(id, updatedSource, period)
    if not checkReady("trades") or not checkReady("summary") then
        return;
    end
   


   
   
   
           -- update indicators values
    ST:update(core.UpdateLast);
    ADX:update(core.UpdateLast);


   
    -- update expressions
    -- processing of Activation points
    if id==id_source then --Updates handler of 'source' datasource ('tf'  timeframe)


   if HH5followed5LL >0 then
if source.close[ period] > source.close[ period-1]
and source.high[ period] > source.high[ period-1]
and source.close[ period-1] > source.close[ period-2]
and source.high[ period-1] > source.high[ period-2]
and source.close[ period-2] > source.close[ period-3]
and source.high[ period-2] > source.high[ period-3]
and source.close[ period-3] > source.close[ period-4]
and source.high[ period-3] > source.high[ period-4]
and source.close[ period-4] > source.close[ period-5]
and source.high[ period-4] > source.high[ period-5]



and source.close[ period-5] < source.close[ period-6]
and source.low[ period-5] < source.low[ period-6]
and source.close[ period-6] < source.close[ period-7]
and source.low[ period-6] < source.low[ period-7]
and source.close[ period-7] < source.close[ period-8]
and source.low[ period-7] < source.low[ period-8]
and source.close[ period-8] < source.close[ period-9]
and source.low[ period-8] < source.low[ period-9]
and source.close[ period-9] < source.close[ period-10]
and source.low[ period-9] < source.low[ period-10]
      and ST.DATA:colorI(period) ==  core.rgb(0, 255, 0)
      and ADX.DATA[ period]> ADX_Level


then

               if mAllowTrade then createTrueMarketOrder("B", Amount, symbol, stop, false, 50); end
                if mAllowTrade then  close("S", core.host:findTable("offers"):find("Instrument", symbol).OfferID); end

      end

      
if source.close[ period] < source.close[ period-1]
and source.high[ period] < source.high[ period-1]
and source.close[ period-1] < source.close[ period-2]
and source.high[ period-1] < source.high[ period-2]
and source.close[ period-2] < source.close[ period-3]
and source.high[ period-2] < source.high[ period-3]
and source.close[ period-3] < source.close[ period-4]
and source.high[ period-3] < source.high[ period-4]
and source.close[ period-4] < source.close[ period-5]
and source.high[ period-4] < source.high[ period-5]



and source.close[ period-5] > source.close[ period-6]
and source.low[ period-5] > source.low[ period-6]
and source.close[ period-6] > source.close[ period-7]
and source.low[ period-6] > source.low[ period-7]
and source.close[ period-7] > source.close[ period-8]
and source.low[ period-7] > source.low[ period-8]
and source.close[ period-8] > source.close[ period-9]
and source.low[ period-8] > source.low[ period-9]
and source.close[ period-9] > source.close[ period-10]
and source.low[ period-9] > source.low[ period-10]
      and ST.DATA:colorI(period) ==  core.rgb(255, 0, 0)
      and ADX.DATA[ period]> ADX_Level

then

               if mAllowTrade then createTrueMarketOrder("S", Amount, symbol, stop, false, 50); end
                if mAllowTrade then  close("B", core.host:findTable("offers"):find("Instrument", symbol).OfferID); end

      end

end


   if HH4followed4LL >0 then
if source.close[ period] > source.close[ period-1]
and source.high[ period] > source.high[ period-1]
and source.close[ period-1] > source.close[ period-2]
and source.high[ period-1] > source.high[ period-2]
and source.close[ period-2] > source.close[ period-3]
and source.high[ period-2] > source.high[ period-3]
and source.close[ period-3] > source.close[ period-4]
and source.high[ period-3] > source.high[ period-4]



and source.close[ period-4] < source.close[ period-5]
and source.low[ period-4] < source.low[ period-5]
and source.close[ period-5] < source.close[ period-6]
and source.low[ period-5] < source.low[ period-6]
and source.close[ period-6] < source.close[ period-7]
and source.low[ period-6] < source.low[ period-7]
and source.close[ period-7] < source.close[ period-8]
and source.low[ period-7] < source.low[ period-8]
      and ST.DATA:colorI(period) ==  core.rgb(0, 255, 0)
      and ADX.DATA[ period]> ADX_Level


then

               if mAllowTrade then createTrueMarketOrder("B", Amount, symbol, stop, false, 50); end
                if mAllowTrade then  close("S", core.host:findTable("offers"):find("Instrument", symbol).OfferID); end

      end

      
if source.close[ period] < source.close[ period-1]
and source.high[ period] < source.high[ period-1]
and source.close[ period-1] < source.close[ period-2]
and source.high[ period-1] < source.high[ period-2]
and source.close[ period-2] < source.close[ period-3]
and source.high[ period-2] < source.high[ period-3]
and source.close[ period-3] < source.close[ period-4]
and source.high[ period-3] < source.high[ period-4]



and source.close[ period-4] > source.close[ period-5]
and source.low[ period-4] > source.low[ period-5]
and source.close[ period-5] > source.close[ period-6]
and source.low[ period-5] > source.low[ period-6]
and source.close[ period-6] > source.close[ period-7]
and source.low[ period-6] > source.low[ period-7]
and source.close[ period-7] > source.close[ period-8]
and source.low[ period-7] > source.low[ period-8]
      and ST.DATA:colorI(period) ==  core.rgb(255, 0, 0)
      and ADX.DATA[ period]> ADX_Level

then

               if mAllowTrade then createTrueMarketOrder("S", Amount, symbol, stop, false, 50); end
                if mAllowTrade then  close("B", core.host:findTable("offers"):find("Instrument", symbol).OfferID); end

      end

end


   if HH3followed3LL >0 then
if source.close[ period] > source.close[ period-1]
and source.high[ period] > source.high[ period-1]
and source.close[ period-1] > source.close[ period-2]
and source.high[ period-1] > source.high[ period-2]
and source.close[ period-2] > source.close[ period-3]
and source.high[ period-2] > source.high[ period-3]



and source.close[ period-3] < source.close[ period-4]
and source.low[ period-3] < source.low[ period-4]
and source.close[ period-4] < source.close[ period-5]
and source.low[ period-4] < source.low[ period-5]
and source.close[ period-5] < source.close[ period-6]
and source.low[ period-5] < source.low[ period-6]
      and ST.DATA:colorI(period) ==  core.rgb(0, 255, 0)
      and ADX.DATA[ period]> ADX_Level


then

               if mAllowTrade then createTrueMarketOrder("B", Amount, symbol, stop, false, 50); end
                if mAllowTrade then  close("S", core.host:findTable("offers"):find("Instrument", symbol).OfferID); end

      end

      
if source.close[ period] < source.close[ period-1]
and source.high[ period] < source.high[ period-1]
and source.close[ period-1] < source.close[ period-2]
and source.high[ period-1] < source.high[ period-2]
and source.close[ period-2] < source.close[ period-3]
and source.high[ period-2] < source.high[ period-3]



and source.close[ period-3] > source.close[ period-4]
and source.low[ period-3] > source.low[ period-4]
and source.close[ period-4] > source.close[ period-5]
and source.low[ period-4] > source.low[ period-5]
and source.close[ period-5] > source.close[ period-6]
and source.low[ period-5] > source.low[ period-6]
      and ST.DATA:colorI(period) ==  core.rgb(255, 0, 0)
      and ADX.DATA[ period]> ADX_Level

then

               if mAllowTrade then createTrueMarketOrder("S", Amount, symbol, stop, false, 50); end
                if mAllowTrade then  close("B", core.host:findTable("offers"):find("Instrument", symbol).OfferID); end

      end

end










   
   
end


   
       if id==id_source2 then --Updates handler of 'source' datasource ('tf'  timeframe)

         if PLAYLIMIT>0 then

if getGrossPL(symbol) > limit then stop7 = getGrossPL(symbol)/dieresi  if stop7>stop8 then stop8=stop7 end end
if getGrossPL(symbol) < stop8 then
                if mAllowTrade then  close("B", core.host:findTable("offers"):find("Instrument", symbol).OfferID); end
                if mAllowTrade then  close("S", core.host:findTable("offers"):find("Instrument", symbol).OfferID); end
    stop8 = instance.parameters.stop8;
    limit = instance.parameters.limit;

   end



   end

   
   end
   
   
   
   










end









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

-----------------------------------------------------------
--Enters to the market
--   side: B - BUY or S - SELL
--   amount: order amount
--   instrumentName: instrument of order
--   stop:  0, 1 or greater value
--   isTrailingStop: true/false
--   limit: 0, 1 or greater value
-----------------------------------------------------------
function createTrueMarketOrder(side, amount, instrumentName, stop, isTrailingStop, limit)
    if not mAllowTrade then
        return;
    end
   
    local offerId = core.host:findTable("offers"):find("Instrument", instrumentName).OfferID;     
   
    if not (mAllowedSide == "Both" or (mAllowedSide == "Buy" and side == "B") or (mAllowedSide == "Sell" and side == "S")) then
        return;
    end
   
    if not mAllowMultiplePositions then
       if (side == 'B' and countLongPositions(instrumentName) > 0) then
           return;
       elseif (side == 'S' and countShortPositions(instrumentName) > 0) then
           return;
       end
    end
   
   
    local valuemap;
   
    valuemap = core.valuemap();
    valuemap.Command = "CreateOrder";
    valuemap.OrderType = "OM";
    valuemap.OfferID = offerId;
    valuemap.AcctID = mAccount;
    valuemap.GTC = "FOK"; --Fill or Kill order to avoid partial execution
    valuemap.Quantity = amount * mLotSize;
    valuemap.BuySell = side;
    valuemap.CustomID = mCID;
    if stop >= 1 then
        valuemap.PegTypeStop = "M";
        if side == "B" then
            valuemap.PegPriceOffsetPipsStop = - stop;
        else
            valuemap.PegPriceOffsetPipsStop = stop;
        end
        if isTrailingStop then
           valuemap.TrailStepStop = 1;
        end
    end
    if limit >= 1 then
        valuemap.PegTypeLimit = "M";
        if side == "B" then
            valuemap.PegPriceOffsetPipsLimit = limit;
        else
            valuemap.PegPriceOffsetPipsLimit = -limit;
        end
    end

    if (not canClose(instrumentName)) and (stop >= 1 or limit >= 1) then
        valuemap.EntryLimitStop = 'Y'
    end
   
    success, msg = terminal:execute(200, valuemap);
    assert(success, msg);
end



-----------------------------------------------------------
-- closes all positions of the specified direction (B for buy, S for sell)
-----------------------------------------------------------
function canClose(instrumentName)
    return core.host:execute("getTradingProperty", "canCreateMarketClose", instrumentName, mAccount);
end

function close(side, offer)
    local enum, row, valuemap;

    enum = core.host:findTable("trades"):enumerator();
    while true do
        row = enum:next();
        if row == nil then
            break;
        end
        if row.AccountID == mAccount and
           row.OfferID == offer and
           row.BS == side and
           row.QTXT == mCID then
            -- if trade has to be closed

            if canClose(row.Instrument) then
                -- create a close market order when hedging is allowed
                valuemap = core.valuemap();
                valuemap.OrderType = "CM";
                valuemap.OfferID = offer;
                valuemap.AcctID = mAccount;
                valuemap.Quantity = row.Lot;
                valuemap.TradeID = row.TradeID;
                valuemap.CustomID = mCID;
                if row.BS == "B" then
                    valuemap.BuySell = "S";
                else
                    valuemap.BuySell = "B";
                end
                success, msg = terminal:execute(200, valuemap);
                assert(success, msg);
            else               
                -- create an opposite market order when FIFO
                valuemap = core.valuemap();
                valuemap.OrderType = "OM";
                valuemap.OfferID = offer;
                valuemap.AcctID = mAccount;
                valuemap.Quantity = row.Lot;
                valuemap.CustomID = mCID;
                if row.BS == "B" then
                    valuemap.BuySell = "S";
                else
                    valuemap.BuySell = "B";
                end
                success, msg = terminal:execute(200, valuemap);
                assert(success, msg);
            end
        end
    end
end

-----------------------------------------------------------
--Handle command execution result
-----------------------------------------------------------
function ExtAsyncOperationFinished(cookie, success, message)
    if cookie == 1 then
        loaded = true;
    elseif cookie == 200 then
        assert(success, message);
    end
   
end

-----------------------------------------------------------
-- Helper functions
-----------------------------------------------------------
function getOppositeSide(side)
    if(side == "B") then
        return "S";
    else
        return "B";
    end
end

function getDSPeriod(ds, updatedSource, period)
    local p;
    if ds:isBar() then
        p = core.findDate(ds.open, updatedSource:date(period), false);
    else
        p = core.findDate(ds, updatedSource:date(period), false);
    end
    if (p > ds:size() - 1) then
        p = ds:size() - 1;
    elseif (p < ds:first()) then
        p = ds:first();
    end
    return p;
end


-----------------------------------------------------------
-- Allow to calculate last closed bar period for ds datasource
-- which has not tick frequency updates
-----------------------------------------------------------
function getClosedPeriod(ds, supposedPeriod)
    --Check if datasource lastdate is closed on updatePeriod or shift supposedPeriod to -1
    if _gUpdatePeriods[ds] == 't1' or _gUpdatePeriods[ds] == nil then
        return supposedPeriod;
    else
        return supposedPeriod - 1;
    end
end

-----------------------------------------------------------
--Helper functions to wrap the table's method call into the simple function call
-----------------------------------------------------------
function streamSize(stream)
    return stream:size();
end

function streamHasData(stream, period)
    return stream:hasData(period);
end

function canCalculate(stream, period)
    return (period >= 0) and (period > stream:first()) and streamHasData(stream, period);
end

-----------------------------------------------------------
-- Helper functions to be sure that you work with a tick stream
-----------------------------------------------------------
function getTickStreamOfPriceType(stream, priceType)
    if stream:isBar() then
        if priceType == "open" then
            return stream.open;
        elseif priceType == "high" then
            return stream.high;   
        elseif priceType == "low" then
            return stream.low;
        elseif priceType == "close" then
            return stream.close;
        elseif priceType == "typical" then
            return stream.typical;
        elseif priceType == "weighted" then
            return stream.weighted;
        elseif priceType == "volume" then
            return stream.volume;
        else
            return stream.close;
        end
    else
       return stream;
    end
end

function selectStream(safeStream, subStream)
    if safeStream:isBar() then
       return subStream;
    else
       return safeStream;
    end
end

---------------------------------------------------------
-- Subscription for updates by datasource timeframe
---------------------------------------------------------

-- subscribe for the price data
function ExtSubscribe(id, instrument, period, bid, type)
    local sub = {};
    if instrument == nil and period == "t1" then
        if bid then
            sub.stream = instance.bid;
        else
            sub.stream = instance.ask;
        end
        sub.tick = true;
        sub.loaded = true;
        sub.lastSerial = -1;
        _gSubscription[id] = sub;
    elseif instrument == nil then
        sub.stream = core.host:execute("getHistory", id, instance.bid:instrument(), period, 0, 0, bid);
        sub.tick = false;
        sub.loaded = false;
        sub.lastSerial = -1;
        _gSubscription[id] = sub;
    else
        sub.stream = core.host:execute("getHistory", id, instrument, period, 0, 0, bid);
        sub.tick = (period == "t1");
        sub.loaded = false;
        sub.lastSerial = -1;
        _gSubscription[id] = sub;
    end
    _gUpdatePeriods[sub.stream] = period;
    if sub.tick then
        return sub.stream;
    else
        if type == "open" then
            _gUpdatePeriods[sub.stream.open] = period;
            return sub.stream.open;
        elseif type == "high" then
            _gUpdatePeriods[sub.stream.high] = period;
            return sub.stream.high;
        elseif type == "low" then
            _gUpdatePeriods[sub.stream.low] = period;
            return sub.stream.low;
        elseif type == "close" then
            _gUpdatePeriods[sub.stream.close] = period;
            return sub.stream.close;
        elseif type == "bar" then
            _gUpdatePeriods[sub.stream.open] = period;
            _gUpdatePeriods[sub.stream.high] = period;
            _gUpdatePeriods[sub.stream.low] = period;
            _gUpdatePeriods[sub.stream.close] = period;
            _gUpdatePeriods[sub.stream.median] = period;
            _gUpdatePeriods[sub.stream.typical] = period;
            _gUpdatePeriods[sub.stream.volume] = period;
            _gUpdatePeriods[sub.stream.weighted] = period;
            return sub.stream;
        else
            assert(false, type .. " is unknown");
        end
    end
end

function AsyncOperationFinished(cookie, success, message)
    local sub;
    sub = _gSubscription[cookie];
    if sub ~= nil then
        sub.loaded = true;
        if sub.stream:size() > 1 then
           sub.lastSerial = sub.stream:serial(sub.stream:size() - 1);
        end
    else
        -- unknown cookie
        if ExtAsyncOperationFinished ~= nil then
            ExtAsyncOperationFinished(cookie, success, message)
        end
    end
end

function Update()
    if instance.bid:size() > 0 then
        _gLastTime = instance.bid:date(instance.bid:size() - 1);
    end
    for k, v in pairs(_gSubscription) do
        if v.loaded and v.stream:size() > 1 then
            local s = v.stream:serial(v.stream:size() - 1);
            local p;
            if s ~= v.lastSerial then
                if v.tick then
                    p = v.stream:size() - 1;    -- the last tick
                else
                    p = v.stream:size() - 2;    -- the previous candle
                end
                ExtUpdate(k, v.stream, p);
                v.lastSerial = s;
            end
        end
    end
end

---------------------------------------------------------
-- Additional functions
---------------------------------------------------------
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 checkSummaryRow(sInstrument)
    local sOfferID, summaryIter, summaryRow;
   
    if mSummaries[sInstrument] ~= nil then
        --try refresh
        if not (mSummaries[sInstrument]:refresh()) then
            mSummaries[sInstrument] = nil;
        end
    end
   
    --re-read all cache
    if mSummaries[sInstrument] == nil then
        sOfferID = core.host:findTable("offers"):find("Instrument", sInstrument).OfferID;
        summaryIter = core.host:findTable("summary"):enumerator();
        summaryRow = summaryIter:next();
        while summaryRow ~= nil do
            if summaryRow.OfferID == sOfferID then
                mSummaries[sInstrument] = summaryRow;
                break;
            end
            summaryRow = summaryIter:next();
        end
    end
end

function getEquity()
   
    checkAccountRow();
    return mAccountRow.Equity;
end

function getBalance()
    checkAccountRow();
    return mAccountRow.Balance;
end

function getProfit()
    checkAccountRow();
    return mAccountRow.Equity - mAccountRow.Balance;
end

function getAmountK(sInstrument)
    local res;
    checkSummaryRow(sInstrument);
    res = mSummaries[sInstrument];
    if res == nil then
        return 0;
    else
        return res.AmountK;
    end
end

function getGrossPL(sInstrument)
    local res;
    checkSummaryRow(sInstrument);
    res = mSummaries[sInstrument];
    if res == nil then
        return 0;
    else
        return res.GrossPL;
    end
end

function getNetPL(sInstrument)
    local res;
    checkSummaryRow(sInstrument);
    res = mSummaries[sInstrument];
    if res == nil then
        return 0;
    else
        return res.NetPL;
    end
end

function getSellAmountK(sInstrument)
    local res;
    checkSummaryRow(sInstrument);
    res = mSummaries[sInstrument];
    if res == nil then
        return 0;
    else
        return res.SellAmountK;
    end
end

function getBuyAmountK(sInstrument)
    local res;
    checkSummaryRow(sInstrument);
    res = mSummaries[sInstrument];
    if res == nil then
        return 0;
    else
        return res.BuyAmountK;
    end
end

function getBuyNetPLPip(sInstrument)
    local res;
    checkSummaryRow(sInstrument);
    res = mSummaries[sInstrument];
    if res == nil then
        return 0;
    else
        return res.BuyNetPLPip;
    end
end

function getSellNetPLPip(sInstrument)
    local res;
    checkSummaryRow(sInstrument);
    res = mSummaries[sInstrument];
    if res == nil then
        return 0;
    else
        return res.SellNetPLPip;
    end
end

function getBuyNetPL(sInstrument)
    local res;
    checkSummaryRow(sInstrument);
    res = mSummaries[sInstrument];
    if res == nil then
        return 0;
    else
        return res.BuyNetPL;
    end
end

function getSellNetPL(sInstrument)
    local res;
    checkSummaryRow(sInstrument);
    res = mSummaries[sInstrument];
    if res == nil then
        return 0;
    else
        return res.SellNetPL;
    end
end


function countPositions(sInstrument)
    local tradesIter, tradeRow, count, sOfferID;
    count = 0;
    if sInstrument ~= nil then
        sOfferID = core.host:findTable("offers"):find("Instrument", sInstrument).OfferID;
    end
    tradesIter = core.host:findTable("trades"):enumerator();
    tradeRow = tradesIter:next();
    while tradeRow ~= nil do
        if (sInstrument == nil or tradeRow.OfferID == sOfferID) then
            count = count + 1;
        end
        tradeRow = tradesIter:next();
    end
    return count;
end

function countLongPositions(sInstrument)
    local tradesIter, tradeRow, count, sOfferID;
    count = 0;
    if sInstrument ~= nil then
        sOfferID = core.host:findTable("offers"):find("Instrument", sInstrument).OfferID;
    end
    tradesIter = core.host:findTable("trades"):enumerator();
    tradeRow = tradesIter:next();
    while tradeRow ~= nil do
        if ((sInstrument==nil or tradeRow.OfferID == sOfferID) and tradeRow.BS == "B") then
            count = count + 1;
        end
        tradeRow = tradesIter:next();
    end
    return count;
end

function countShortPositions(sInstrument)
    local tradesIter, tradeRow, count, sOfferID;
    count = 0;
    if sInstrument ~= nil then
        sOfferID = core.host:findTable("offers"):find("Instrument", sInstrument).OfferID;
    end
    tradesIter = core.host:findTable("trades"):enumerator();
    tradeRow = tradesIter:next();
    while tradeRow ~= nil do
        if ((sInstrument == nil or tradeRow.OfferID == sOfferID) and tradeRow.BS == "S") then
            count = count + 1;
        end
        tradeRow = tradesIter:next();
    end
    return count;
end

function getLastUpdateTime()
    if (_gLastTime == nil) then
        return 0;
    else
        return _gLastTime;
    end
end

function time(hours, minutes, seconds)
    local dtLast;
    dtLast = core.dateToTable(_gLastTime);
    if seconds == nil then
        seconds = 0;
    end
    return core.datetime(dtLast.year, dtLast.month, dtLast.day, hours, minutes, seconds);
end

function isValidDate(checkDate)
   if (checkDate < 1) then
       return false;
   else
       return true;
   end
end

function parseTime(sTime)
    local iDelimHMPos = string.find(sTime, ":");
    local h = tonumber(string.sub(sTime, 1, iDelimHMPos - 1));
    local sTimeTile = string.sub(sTime, iDelimHMPos + 1);
    local iDelimMSPos = string.find(sTimeTile, ":");
    local m, s;
    s = 0;
    if iDelimMSPos == nil then
        m = tonumber(sTimeTile);
    else
        m = tonumber(string.sub(sTimeTile, 1, iDelimMSPos - 1));
        s = tonumber(string.sub(sTimeTile, iDelimMSPos + 1));
    end
    return time(h, m, s);
end

function getPipSize(sInstrument)
    return core.host:findTable("offers"):find("Instrument", sInstrument).PointSize;
end






What i need is that:
If the order failed to execute ,
to try to reopen the position
in the range of 10 pips.

If there is a slippage bigger of 10 pips from the price it tried to open the position ,
then it should stop trying to open it..
Is that possible?


You can save valuemap somewhere and then reuse it in ExtAsyncOperationFinished:
elseif cookie == 200 then
if not success and StillWantToOpenTrade() then
success, msg = terminal:execute(200, last_valuemap);
end
end
Something like this
“There are only three sports: bullfighting, motor racing, and mountaineering; all the rest are merely games.” (c) Ernest Hemingway
Victor.Tereschenko
FXCodeBase: Confirmed User
 
Posts: 144
Joined: Fri Nov 19, 2010 8:55 am


Return to Indicator and Signal Requests

Who is online

Users browsing this forum: No registered users and 9 guests