stevehopwoodforex.com
https://www.stevehopwoodforex.com/phpBB3/
Print view

Desky. TDesk's trading drone.
https://www.stevehopwoodforex.com/phpBB3/viewtopic.php?t=5545
Page 14 of 50
Author:  SteveHopwood [ Tue Nov 27, 2018 7:01 pm ]
Post subject:  This is driving me nuts

I occasionally get an Array Out of Range error, thrown up by this line of code:
if (TimeCurrent() >= TimeToStartTrading[pairIndex])
with TimeToStartTrading[pairIndex]being the culprit.

Thingy is, none of the other arrays do this. Do a search for TimeToStartTrading to see where it is declared, resized etc. You can see that I am resizing it at ArraySize(TDeskSymbols) + 10.

Can any of you code slingers see anything wrong?

:xm: :rocket:
Author:  SteveHopwood [ Tue Nov 27, 2018 9:06 pm ]
Post subject:  Desky. TDesk's trading drone.

Folks, my limited brain capacity has just given up. It is exam week and I am seriously pulled out.

Re c1borg's pending trade thingy, I know where the problems lie and how to correct them and hope to do so on Friday. I just tried but the two glasses of wine with my dinner have rendered coding an not-good thingy to try to do.

Re hedging, those of you who had hedge trades rapidly opening and closing are still on your own.

I received this earlier from Leon:
Hi Steve,

Sorry for the false alarm. The first hedge went of fine with EurUsd and I thought all is ok. When I saw the second trade in the opposite direction with EurJpy there was no hedge trade opened. I closed the Ea an re attached it to see if it would not solve the problem but still no hedge trade. There are also other trades in the opposite direction with no hedge trades. I decided to close the hedge trade with EurUsd and immediately a hedge trade opened with EurJpy. From what I can see is that the Ea is only allowing one hedge trade at a time to be opened with all the currency pairs that I am trading.
I know where to look - just haven't the mental capacity to look right now. I will solve this also with my next update.

:xm: :rocket:
Author:  SteveHopwood [ Wed Nov 28, 2018 5:23 am ]
Post subject:  Desky. TDesk's trading drone.

V 2g is in post 1, in response to this PM from Simon:
syhchan wrote:Steve,

Did you get the error when you first start up the MT desktop? I think it is a timing issue. The sizing of the array in OnInit() depends on ReadTDeskSignals(). ReadTDeskSignals() in turn depends on the availability of TDesk EA which starts in parallel with Desky. Chances is that Desky initializes before TDesk which can cause the array size set to 0. Adding a delay could resolve the issue.

Just my 2 cents,
Simon

Subject: Desky. TDesk's trading drone.
I shut down and restarted the crapform and hey presto - instant array out of range error. 2g appears to have fixed this.

DIYers, insert this at the top of OnInit():

Code: Select all

   //Give TDesk time to get going
   Comment("Waiting for TDesk to initialise.....");
   Sleep(10000);
Thanks Simon. :clap: :clap: :clap: :clap: :clap:

:xm: :rocket:
Author:  SteveHopwood [ Wed Nov 28, 2018 7:32 am ]
Post subject:  Desky. TDesk's trading drone.

V 2h is in post 1, with two more fixes. Leon sent me this pm last night:
Wavegarrick wrote:Subject: Desky. TDesk's trading drone.

Hi Steve,

Sorry for the false alarm. The first hedge went of fine with EurUsd and I thought all is ok. When I saw the second trade in the opposite direction with EurJpy there was no hedge trade opened. I closed the Ea an re attached it to see if it would not solve the problem but still no hedge trade. There are also other trades in the opposite direction with no hedge trades. I decided to close the hedge trade with EurUsd and immediately a hedge trade opened with EurJpy. From what I can see is that the Ea is only allowing one hedge trade at a time to be opened with all the currency pairs that I am trading.

I am attaching a picture with the trades as mentioned above

I hope I am understanding the hedging feature correctly.

Cheers
Leon
DIYers, do a search for, "//We need to know the the position is hedged to prevent order closure further down" and look down three lines. The first conditional is, "if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES))". This checks that the trade has not been closed. There are no further checks, so all open trades are examined and once a hedge is discovered then a variable is set to tell Desky that there is a hedge in place, so he cannot add hedges to other pairs. Add these two conditionals:

Code: Select all

      if (OrderSymbol() != symbol)
         continue;
      if (OrderMagicNumber() != MagicNumber)
         continue;
The second fix is adding the code that allows Desky to send stop and limit orders rather than an immediate market trade. DIYers, do a search for, "bool LookForTradingOpportunities(string symbol, int pairIndex, int type)" and replace the entire function with:

Code: Select all

bool LookForTradingOpportunities(string symbol, int pairIndex, int type)
{
//return;//TEMPORARY. REMOVE LATER
   
   GetBasics(symbol);
   double take = 0, stop = 0, price = 0;
   bool SendTrade = false, result = false;

   double SendLots = Lot;
   //Check filters
   if (!IsTradingAllowed(symbol, pairIndex) ) return(false);
   
   /////////////////////////////////////////////////////////////////////////////////////
   
   //Trading decision.
   bool SendLong = false, SendShort = false;

   //Long trade
   
   //Specific system filters
   if (BuySignal) 
      SendLong = true;
   
   //Usual filters
   if (SendLong)
   {
      
      if (UseZeljko && !BalancedPair(symbol, OP_BUY) ) return(false);
      
   }//if (SendLong)
   
   /////////////////////////////////////////////////////////////////////////////////////

   if (!SendLong)
   {
      //Short trade
      //Specific system filters
      if (SellSignal) 
         SendShort = true;
      
      if (SendShort)
      {      
         //Usual filters

         //Other filters
           
         if (UseZeljko && !BalancedPair(symbol, OP_SELL) ) return(false);
         
      }//if (SendShort)
      
   }//if (!SendLong)
     

////////////////////////////////////////////////////////////////////////////////////////
   
   
   //Long 
   if (SendLong)
   {
       
      price = NormalizeDouble(MarketInfo(symbol, MODE_ASK), digits);
      
      //Immediate market trade need no further adjustment
      
      
      //Buy stop
      if (type == OP_BUYSTOP)
         price = NormalizeDouble(price + (DistanceFromMarket / factor), digits);
         
      //Buy limit
      if (type == OP_BUYLIMIT)
         price = NormalizeDouble(price - (DistanceFromMarket / factor), digits);
         
      stop = CalculateStopLoss(symbol, OP_BUY, price);
         
         
      take = CalculateTakeProfit(symbol, OP_BUY, price);
      
      
      //Lot size calculated by risk
      if (!CloseEnough(RiskPercent, 0)) SendLots = CalculateLotSize(symbol, price, stop );

               
      SendTrade = true;
      
   }//if (SendLong)
   
   //Short
   if (SendShort)
   {
      
      price = NormalizeDouble(MarketInfo(symbol, MODE_BID), digits);


      //Immediate market trade need no further adjustment

      //Sell stop
      if (type == OP_SELLSTOP)
         price = NormalizeDouble(price - (DistanceFromMarket / factor), digits);
         
      //Sell limit
      if (type == OP_SELLLIMIT)
         price = NormalizeDouble(price + (DistanceFromMarket / factor), digits);
         
      
      stop = CalculateStopLoss(symbol, OP_SELL, price);
         
      take = CalculateTakeProfit(symbol, OP_SELL, price);
      
      
      //Lot size calculated by risk
      if (!CloseEnough(RiskPercent, 0)) SendLots = CalculateLotSize(symbol, price, stop);

      
         
      SendTrade = true;      
   
      
   }//if (SendShort)
   

   if (SendTrade)
   {
      
      result = true;//Allow sending the grid if not sending an immediate market trade
      
      //if (SendImmediateMarketTrade)
      result = SendSingleTrade(symbol, type, TradeComment, SendLots, price, stop, take);

      if (result)
      {
         //The latest garbage from the morons at Crapperquotes appears to occasionally break Matt's OR code, so tell the
         //ea not to trade for a while, to give time for the trade receipt to return from the server.
         TimeToStartTrading[pairIndex] = TimeCurrent() + PostTradeAttemptWaitSeconds;
        
              
         //if (BetterOrderSelect(TicketNo, SELECT_BY_TICKET, MODE_TRADES) )
           // CheckTpSlAreCorrect(type);
            
        
      }//if (result)          
      
      
   }//if (SendTrade)   

   return(result);
   

}//End bool LookForTradingOpportunities(string symbol, int PairIndex)
The more advanced of you will easily spot the few lines of code I have added. This sends the trades. You still need to add the code that calls the function. Search for, "if (!StopTrading)". This heads up quite a large code block, so easiest is to copy this over the top of the existing block:

Code: Select all

      if (!StopTrading)
      {
         if (TimeCurrent() >= TimeToStartTrading[pairIndex])
         {
            if (OpenTrades == 0)
            {
               if (BuySignal || SellSignal)
               {
                 if (BuySignal)
                 {
                     //Immediate market trade
                     if (SendImmediateMarketTrade)
                        result = LookForTradingOpportunities(symbol, pairIndex, OP_BUY);
                     
                     //Pending orders
                     if (SendPendingTrades)
                     {
                        if (TypeOfPendingTrade == Buy_stop)
                           result = LookForTradingOpportunities(symbol, pairIndex, OP_BUYSTOP);
                           
                        if (TypeOfPendingTrade == Buy_limit)
                           result = LookForTradingOpportunities(symbol, pairIndex, OP_BUYLIMIT);
                           
                        if (TypeOfPendingTrade == Buy_stop_and_buy_limit)
                        {
                           result = LookForTradingOpportunities(symbol, pairIndex, OP_BUYSTOP);
                           
                           Sleep(5000);//Give the platform time to catch up
                           
                           result = LookForTradingOpportunities(symbol, pairIndex, OP_BUYLIMIT);
                        }//if (TypeOfPendingTrade == Buy_stop_and_buy_limit)
                        
                           
                     }//if (SendPendingTrades)
                     
                     
                     if (UseGridTrading)
                        if (result)
                        {
                           if (TypeOfGrid == Stop || TypeOfGrid == Both)
                           {
                              SendBuyGrid(symbol, OP_BUYSTOP, ask + (DistanceFromMarket / factor), Lot );
                           }//if (TypeOfGrid == OP_BUYSTOP || TypeOfGrid == Both)
                           
                           if (TypeOfGrid == Limit || TypeOfGrid == Both)
                           {
                              SendBuyGrid(symbol, OP_BUYLIMIT, ask - (DistanceFromMarket / factor), Lot );
                           }//if (TypeOfGrid == OP_BUYSTOP || TypeOfGrid == Both)
                           
                        }//if (result)
                     
                  }//if (BuySignal)

                     
                  if (SellSignal)
                  {
                     
                     //Immediate market trade
                     if (SendImmediateMarketTrade)   
                        result = LookForTradingOpportunities(symbol, pairIndex, OP_SELL);
                     
                     //Pending orders
                     if (SendPendingTrades)
                     {
                        if (TypeOfPendingTrade == Sell_Stop)
                           result = LookForTradingOpportunities(symbol, pairIndex, OP_SELLSTOP);
                           
                        if (TypeOfPendingTrade == Sell_limit)
                           result = LookForTradingOpportunities(symbol, pairIndex, OP_SELLLIMIT);
                           
                        if (TypeOfPendingTrade == Sell_stop_and_sell_limit)
                        {
                           result = LookForTradingOpportunities(symbol, pairIndex, OP_SELLSTOP);
                           
                           Sleep(5000);//Give the platform time to catch up
                           
                           result = LookForTradingOpportunities(symbol, pairIndex, OP_SELLLIMIT);
                        }//if (TypeOfPendingTrade == Sell_stop_and_sell_limit)
                        
                           
                     }//if (SendPendingTrades)

                     if (UseGridTrading)
                        if (result)
                        {
                           if (TypeOfGrid == Stop || TypeOfGrid == Both)
                           {
                              SendSellGrid(symbol, OP_SELLSTOP, bid - (DistanceFromMarket / factor), Lot );
                           }//if (TypeOfGrid == OP_SELLSTOP || TypeOfGrid == Both)
                           
                           if (TypeOfGrid == Limit || TypeOfGrid == Both)
                           {
                              SendSellGrid(symbol, OP_SELLLIMIT, bid + (DistanceFromMarket / factor), Lot );
                           }//if (TypeOfGrid == OP_BUYSTOP || TypeOfGrid == Both)
                           
                        }//if (result)
                     
                  }//if (SellSignal)
                  
                     
                  //This takes care of grid trading only.
                  if (!SendImmediateMarketTrade)
                     if (UseGridTrading)
                     {
                        if (BuySignal)
                        {
                           if (TypeOfGrid == Stop || TypeOfGrid == Both)
                           {
                              SendBuyGrid(symbol, OP_BUYSTOP, ask + (DistanceFromMarket / factor), Lot );
                           }//if (TypeOfGrid == Stop || TypeOfGrid == Both)
                                 
                           if (TypeOfGrid == Limit || TypeOfGrid == Both)
                           {
                              SendBuyGrid(symbol, OP_BUYLIMIT, ask - (DistanceFromMarket / factor), Lot );
                           }//if (TypeOfGrid == Limit || TypeOfGrid == Both)
                           
                        }//if (BuySignal)
                        
                        if (SellSignal)
                        {  
                           if (TypeOfGrid == Stop || TypeOfGrid == Both)
                           {
                              SendSellGrid(symbol, OP_SELLSTOP, bid - (DistanceFromMarket / factor), Lot );
                           }//if (TypeOfGrid == OP_SELLSTOP || TypeOfGrid == Both)
                           
                           if (TypeOfGrid == Limit || TypeOfGrid == Both)
                           {
                              SendSellGrid(symbol, OP_SELLLIMIT, bid + (DistanceFromMarket / factor), Lot );
                           }//if (TypeOfGrid == OP_BUYSTOP || TypeOfGrid == Both)
                        }//if (SellSignal)
                        
                     }//if (UseGridTrading)
                       
                     
               }//if (BuySignal || SellSignal)
               
            }//if (OpenTrades == 0)
            
         }//if (TimeCurrent() >= TimeToStartTrading[PairIndex])
      }//if (!StopTrading)
The sharp-eyed amongst you will see that the above code will need further adaptation if members start to want to send both a pending order rather than an immediate market trade, and a grid of stop/limit orders. Let's cross that bridge if someone builds it.

Not a DIYer yet? Try it - you cannot do any harm. Park a copy of your working version somewhere safe so you can return to it if you muck up. If all else fails, then redownload from post 1. Make the changes and hit the F7 key to recompile the code into machine code; no errors appearing mean you have got it right. It is quite satisfying.


:xm: :rocket:
Author:  c1borg [ Wed Nov 28, 2018 7:49 am ]
Post subject:  Desky. TDesk's trading drone.

Many thanks for the fix Steve :hi:
Author:  Wavegarrick [ Wed Nov 28, 2018 12:30 pm ]
Post subject:  Desky. TDesk's trading drone.

Hi Steve,

Thanks for this. I purposely had a set running with quick turnaround signals to test the hedge feature. 3 hedge trades opened on opposite signals and one hedge trade closed with a signal back in the direction of the original trade.

From this, as far as I can see all looking good :good:

Cheers
Leon
Author:  SteveHopwood [ Wed Nov 28, 2018 4:18 pm ]
Post subject:  Desky. TDesk's trading drone.

Wavegarrick » Wed Nov 28, 2018 12:30 pm wrote:Hi Steve,

Thanks for this. I purposely had a set running with quick turnaround signals to test the hedge feature. 3 hedge trades opened on opposite signals and one hedge trade closed with a signal back in the direction of the original trade.

From this, as far as I can see all looking good :good:

Cheers
Leon
:clap: :clap: :clap: :clap: :clap:

:xm: :rocket:
Author:  c1borg [ Thu Nov 29, 2018 5:03 pm ]
Post subject:  Desky. TDesk's trading drone.

Just worked out I was using the lots per dollup wrongly with a setting of 1000/dollup and 0.01 lot size you get 0.01 from 0 to 2000 and it will change to 0.02 for anything over 2000 equity. I mistakenly thought anything over 1000 would add the extra 0.01 :oops:

As the manual says....
▪Example of use, choosing the equity:
•equity = $2133.56
•LotPerDollopOfCash = 0.01.
•SizeOfDollop = $1,000.
•Calculated lot size is 0.02.
Author:  SteveHopwood [ Mon Dec 03, 2018 2:36 pm ]
Post subject:  Desky. TDesk's trading drone.

Version 2i is in post 1. Peter asked me to add ATR breakeven to mptm, so I have added it here.

Details at http://www.stevehopwoodforex.com/phpBB3 ... 59#p165159.

You can use the first half of the DIY. For the second part, copy this over the top of the existing function:

Code: Select all

void BreakEvenStopLoss(int ticket) // Move stop loss to breakeven
{

   //Security check
   if (!BetterOrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES))
      return;
   
   //No need to continue if already at BE
   if (OrderType() == OP_BUY)
      if (OrderStopLoss() >= OrderOpenPrice() )
         return;
         
   if (OrderType() == OP_SELL)
      if (!CloseEnough(OrderStopLoss(), 0) )//Sell stops need this extra conditional to cater for no stop loss trades
         if (OrderStopLoss() <= OrderOpenPrice() )
            return;
   
   GetBasics(OrderSymbol() );//Make sure that factor is correct. It should be, but no harm to check
      
   //ATR BE
   if (UseAtrBE)
   {
      double val = GetAtr(OrderSymbol(), AtrTimeFrameBE, AtrPeriodBE, AtrShiftBE);
      BreakEvenPips = (val * factor);
   }//if (UseAtrBE)

   GetBasics(OrderSymbol() );
      
   double NewStop = 0;
   bool result = true;
   bool modify=false;
   double sl = OrderStopLoss();
   double target = OrderOpenPrice();
   
   
   if (OrderType()==OP_BUY)
   {
      //if (HiddenPips > 0) target-= (HiddenPips / factor);
      if (bid >= OrderOpenPrice () + (BreakEvenPips / factor) )          
      {
         //Calculate the new stop
         NewStop = NormalizeDouble(OrderOpenPrice()+(BreakEvenProfit / factor), digits);
         modify = true;   
      }//if (bid >= OrderOpenPrice () + (Point*BreakEvenPips) && 
   }//if (OrderType()==OP_BUY)               			         
    
   if (OrderType()==OP_SELL)
   {
     //if (HiddenPips > 0) target+= (HiddenPips / factor);
     if (ask <= OrderOpenPrice() - (BreakEvenPips / factor) ) 
     {
         //Calculate the new stop
         NewStop = NormalizeDouble(OrderOpenPrice()-(BreakEvenProfit / factor), digits);
         modify = true;   
     }//if (ask <= OrderOpenPrice() - (Point*BreakEvenPips) && (OrderStopLoss()>OrderOpenPrice()|| OrderStopLoss()==0))     
   }//if (OrderType()==OP_SELL)

   //Move 'hard' stop loss whether hidden or not. Don't want to risk losing a breakeven through disconnect.
   if (modify)
   {
      if (NewStop == OrderStopLoss() ) return;
      while (IsTradeContextBusy() ) Sleep(100);
      result = ModifyOrder(OrderTicket(), OrderOpenPrice(), NewStop, OrderTakeProfit(), OrderExpiration(), clrNONE, __FUNCTION__, slm);
      if (!result)
         Sleep(10000);//10 seconds before trying again
         
      while (IsTradeContextBusy() ) Sleep(100);
      if (PartCloseEnabled && OrderComment() == TradeComment) bool success = PartCloseOrder(OrderTicket() );
   }//if (modify)
   
} // End BreakevenStopLoss sub

:xm: :rocket:
Author:  PeterUK [ Tue Dec 04, 2018 9:19 pm ]
Post subject:  Desky... has huge potential... :)

I see huge potential for Desky... working alongside with TDesk ;)

I have just converted a manual trading plan that I'm developing in to Desky so that I can automate the process of paper trading, allowing it to forward test with minimal negative emotional/psychological impact.

Desky does what it's programmed to do... pulling the right trigger(S) when it sees a signal or two from TDesk, after evaluating a selection of custom indicators... i.e. SuperSlope, HGI and etc... :D

Possibilities are endless, wherever your imagination takes you :good:

Great work team! Thomas, Steve, et al...
All times are UTC Page 14 of 50