Como enviar uma Ordem, achei os exemplos complicados alguem poderia me dar uma Luz !!!

 

Ola Pessoal , gostaria de apenas enviar uma ordem Compra/Venda com SL e TP 



Enviar_compra(PRECO,STOPLOSS,TAKEPROFIT);


ou Venda ... 



Apenas isso  !!!


Abc

Sandrolho

 

Eu faço assim: Para comprar ou vender chamo funções BuyOrder e SellOrder.

Veja as funções em exemplo abaixo:

//+------------------------------------------------------------------+
//|                                                      media80.mq5 |
//|                                     Copyright 2017, Sérgio Gelli |
//|                                     https://www.ubatumirim.com.br|
//+------------------------------------------------------------------+
#property copyright " Copyright 2016, Sérgio Gelli"
#property link      " https://www.ubatumirim.com.br"
#property version   "1.00"
#property description "EA trades on \"Method areas\""
double lot1               = 1;  // volume
double StopLoss           = 60; 
double TakeProfit         = 12; 
int    MA_Period1         = 22; // Moving Average Period
int    MA_Period2         = 44; // Moving Average Period
input int    EA_Magic           = 12345; // EA Magic Number
//--- global variables
int    contBar=0, MA1,MA2,handle;  
double       ma01[],ma02[];
double price;
//--- input parametres
bool newBar=false;
bool buyExist=false,sellExist=false;
MqlRates mrate[];
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
 //////////////////////////////////////////////////////////////////////////////
 /////////////////// handle do ma01 ///////////////////////////////
 MA1=iMA(_Symbol,_Period,MA_Period1,0,MODE_EMA,PRICE_CLOSE);
 MA2=iMA(_Symbol,_Period,MA_Period2,0,MODE_EMA,PRICE_CLOSE);
 if(MA1<0 || MA2<0)
 {
  Comment("Error Creating Handles for indicators - error: ",GetLastError(),"!!");
  return(-1);
 }
 //---
 return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   IndicatorRelease(handle);
   IndicatorRelease(MA1);
   IndicatorRelease(MA2);
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
 ArraySetAsSeries(mrate,true);
 if(CopyRates(_Symbol,_Period,0,81,mrate)<0)
 {   //sobre as três últimas barras em nosso arranjo Mqlrates
  Alert("Error copying rates/history data - error:",GetLastError(),"!!");
  return;
 }
 ///////////////////////////////////////////////////////////////////////////
 ////////////////////// captura valor do tick ///////////////////
 MqlTick last_tick;
 if(SymbolInfoTick(Symbol(),last_tick))
 {
  Print(last_tick.time,": Bid = ",last_tick.bid,
       " Ask = ",last_tick.ask,"  Volume = ",last_tick.volume);
 }
 else 
  Print("SymbolInfoTick() falhou, erro = ",GetLastError());
 ////////////////////////////////////////////////////////////////////////////////
 /////////////////////contador de Bars //////////////////////////////
 static datetime Old_Time;
 datetime New_Time[3]; // copying the last bar time to New_Time[0]
 int handle_copied=CopyTime(_Symbol,_Period,0,3,New_Time);
 if(handle_copied>0) // ok, the data has been copied successfully
 {
  if(Old_Time!=New_Time[0]) // if old time isn't equal to new bar time
  {
   newBar=true;
   Old_Time=New_Time[0];  // new bar here saving bar time
  }
 }
 /////////////////////////////////////////////////////////////
 //////////////////////// MAs /////////////////////////////////
 ArraySetAsSeries(ma01,true);  // the MA-2 values arrays
 if(CopyBuffer(MA1,0,0,7,ma01)<0)
 {
  Comment(" 0005  -  Error MA1 indicator buffer - error:",GetLastError());
  ResetLastError();
  return;
 }
 ArraySetAsSeries(ma02,true);  // the MA-2 values arrays
 if(CopyBuffer(MA2,0,0,22,ma02)<0)
 {
  Comment(" 0005  -  Error MA2 indicator buffer - error:",GetLastError());
  ResetLastError();
  return;
 }
 ///////////////////////////////////////////////////////////////
 //////////////// posições abertas ou fechadas? ////////////////
 if(PositionSelect(_Symbol)==true) // we have an opened position
 {
  if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
  {
   buyExist=true;
  }
  else
  {
   sellExist=true;
  }
 }
 else
 {
  buyExist=false;
  sellExist=false;
 }
///////////////////////// início //////////////////////////
/////////////////// vender  comprar ///////////////////////
//////////////////// inicio ///////////////////////////////
///////////// nadafaz se esta em posição //////////
 if(sellExist+buyExist>0)
 {
  return;
 }
 if( seus códigos)
 {
  BuyOrder1();
  contBar=0;
 }
 if( seus códigos)
 {
  SellOrder1();
  contBar=0;
 }
 if(newBar)
 {
  newBar=false;

 contBar++;
  return;
 }
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
// vendas
//+------------------------------------------------------------------+
void SellOrder1()
  {
   MqlTradeCheckResult m_check_result;
   MqlTradeResult mresult;             // To be used to get our trade results
   MqlTradeRequest mrequest={0};       // To be used for sending our trade requests
   price=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
   price=NormalizeDouble((price),_Digits);
   double STP=(StopLoss *0.00001);      // *_Point,_Digits
   STP=price+(StopLoss *0.00001);       // *_Point,_Digits
   double TKP=price-(TakeProfit *0.00001);          // *_Point,_Digits
   mrequest.sl = STP;                   // Stop Loss em
   mrequest.tp = TKP;                   // Take Profit em
   mrequest.action= TRADE_ACTION_DEAL;  // immediate order execution
   mrequest.price = price;              // latest ask price
   mrequest.symbol = _Symbol;           // currency pair
   lot1=NormalizeDouble(AccountInfoDouble(ACCOUNT_BALANCE)/1000,2)*2;
   if (lot1>5) lot1=5;
   // o volume é modificado a medida que seu capital é alterado
   mrequest.volume = lot1;                 // number of lots to trade
   mrequest.magic = EA_Magic;              // Order Magic Number
   mrequest.type = ORDER_TYPE_SELL;        // sell Order
   mrequest.type_filling = ORDER_FILLING_FOK;// Order execution type
   mrequest.deviation=100;                  // Deviation from current price
//--- send order
   OrderSend(mrequest,mresult); // abre VENDA
                                //    get the result code
   if(mresult.retcode==10009 || mresult.retcode==10008) //Request is completed or order placed
     {
      //Alert(" 0008  A BUY order has been successfully placed with Ticket#:",mresult.order,"!!");
      Alert("Volume = ",lot1,"  Price = ",price," SL = ",STP," TP = ",TKP," ********* SUCCESS VENDA   SELL  OOOOOOOO0 ");
      estouOperando=true;
     }
   else
     {
      Alert("FALHA ---- LOT =",lot1,"   Price = ",price," Stop Loss = ",STP," Take Profit = ",TKP," XxXXXXXXX    FAIL         SELL  XXXXXXXXXXX ");
      ResetLastError();
     }    // fim if (autorizaOpr==0)
  }
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
// compras
//+------------------------------------------------------------------+
void BuyOrder1()
  {
   MqlTradeCheckResult m_check_result;
   MqlTradeResult mresult;       // To be used to get our trade results
   MqlTradeRequest mrequest={0};  // To be used for sending our trade requests
   price=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
   price=NormalizeDouble((price),_Digits);
   double STP=(StopLoss *0.00001); // *_Point,_Digits
   STP=price-(StopLoss *0.00001);  // *_Point,_Digits
   double TKP=price+(TakeProfit *0.00001);           // *_Point,_Digits
   mrequest.sl = STP;              // Stop Loss em
   mrequest.tp = TKP;              // Take Profit em
   mrequest.action=TRADE_ACTION_DEAL;                                  // immediate order execution
   mrequest.price=price;         // latest ask price
   mrequest.symbol=_Symbol;      // currency pair
   lot1=NormalizeDouble(AccountInfoDouble(ACCOUNT_BALANCE)/1000,2)*2;
   if (lot1>5) lot1=5;
   // o volume é modificado a medida que seu capital é alterado
   mrequest.volume= lot1;       // number of lots to trade
   mrequest.magic = EA_Magic;   // Order Magic Number
   mrequest.type = ORDER_TYPE_BUY; 
   mrequest.type_filling = ORDER_FILLING_FOK;                             // Order execution type
   mrequest.deviation=100;                                                // Deviation from current price
//--- send order
   OrderSend(mrequest,mresult); // abre COMPRA
   if(mresult.retcode==10009 || mresult.retcode==10008) //Request is completed or order placed
   {
   Alert("OOOOOO SUCCESS  OOOOOOO","Volume = ",lot1,"   - Price = ",price,"   SL = ",STP,"   TP = ",TKP);
   }
   else
   {
      Alert("XXXXXXXX    FAIL lot=", lot1,"  Price = ",price,"   Stop Loss = ",STP,"   Take Profit = ",TKP);
      ResetLastError();
   }    // fim if (autorizaOpr==0)
  }
//+------------------------------------------------------------------+


 

Olá,

estude a classe Ctrade fica bem mais fácil de programar. 


//+------------------------------------------------------------------+
//|                                                    Exp_MyRSI.mq5 |
//|                                                  Rogério G.Torres|
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Rogério G. Torres"
#property link      "https://www.mql5.com"
#property version   "1.00"



#include <Trade\Trade.mqh>



     bool Ret=trade.PositionOpen(_Symbol, TipoOrdem, Lote, Preco, Preco_loss, Preco_gain, "Exp_MyRSI");




Documentação sobre MQL5: Biblioteca Padrão / Classes de negociação / CTrade
Documentação sobre MQL5: Biblioteca Padrão / Classes de negociação / CTrade
  • www.mql5.com
Biblioteca Padrão / Classes de negociação / CTrade - Referência sobre algorítimo/automatização de negociação na linguagem para MetaTrader 5
 
Rogerio Giannetti Torres:

Olá,

estude a classe Ctrade fica bem mais fácil de programar. 



Obrigado !!

 Entao estou tentando utilizar ela, e nao sei qual a besteira que estou fazendo. Recebo como erro isso :

CTrade::OrderSend: buy stop 5.00 DOLU17 at 3132.500 [unknown retcode 0]


Isso sai no log do Experts.  mas nao aparece a ordem do dolar que enviei ,,,,....



void ExecutaOrdemCompraAsk (double volume,double precodecompra,string ATIVO,double stoploss ,double takeprofit,string comentario)

{

    double ask=SymbolInfoDouble(_Symbol,SYMBOL_ASK); 

      double buy_stop_price=ask; 

      bool res=trade.BuyStop(5,buy_stop_price,_Symbol); // ou com stoploss trade.Buy(volume,ATIVO,buy_stop_price,stoploss,takeprofit,comentario);

      Print(res);


OBS: Eu fiz um indicador!!? tem que ser isso ?  EA ? "Exp_MyRSI");



Att

Sandrolho

 
sandrolho:

Obrigado !!

 Entao estou tentando utilizar ela, e nao sei qual a besteira que estou fazendo. Recebo como erro isso :

CTrade::OrderSend: buy stop 5.00 DOLU17 at 3132.500 [unknown retcode 0]


Isso sai no log do Experts.  mas nao aparece a ordem do dolar que enviei ,,,,....



void ExecutaOrdemCompraAsk (double volume,double precodecompra,string ATIVO,double stoploss ,double takeprofit,string comentario)

{

    double ask=SymbolInfoDouble(_Symbol,SYMBOL_ASK); 

      double buy_stop_price=ask; 

      bool res=trade.BuyStop(5,buy_stop_price,_Symbol); // ou com stoploss trade.Buy(volume,ATIVO,buy_stop_price,stoploss,takeprofit,comentario);

      Print(res);


OBS: Eu fiz um indicador!!? tem que ser isso ?  EA ? "Exp_MyRSI");



Att

Sandrolho


Pessoal, eu tava fazendo indicador, parece q nao funciona o envio de ordem com indicador. Testei fazendo um EA,.. e a ordem envia... vou pensar como vou fazer, pois o meu indicador tem recursos graficos e no EA, nao consigo usa-los.



Obrigado a ajuda de todos,... show de bola pessoal !! muitos ganhos a todos ... eu opero somente no Dolar WDO e DOL.... em breve forex qdo ficar bom 


abc

 

Olá,

dá uma olhada no artigo abaixo, vai ajudar em muitos seus estudos.

Abç(s).

O uso de bibliotecas de classe de negócio padrão MQL5 ao escrever um Expert Advisor
O uso de bibliotecas de classe de negócio padrão MQL5 ao escrever um Expert Advisor
  • 2014.02.05
  • Samuel Olowoyo
  • www.mql5.com
Este artigo explica como usar as principais funcionalidades das Classes de negócio da biblioteca padrão do MQL5 ao escrever Expert Advisors que implementam o fechamento e modificação de posição, posicionamento de ordem pendente e exclusão e verificação de Margem antes de posicionar um negócio. Também demonstramos como as classes de negócio podem ser usadas para obter detalhes de ordens e transações.
Razão: