Ayuda con la codificación... ¿Cómo puedo hacer que el indicador filtre en lugar de alertar? - página 9
Está perdiendo oportunidades comerciales:
- Aplicaciones de trading gratuitas
- 8 000+ señales para copiar
- Noticias económicas para analizar los mercados financieros
Registro
Entrada
Usted acepta la política del sitio web y las condiciones de uso
Si no tiene cuenta de usuario, regístrese
Una sugerencia a todos los miembros, no utilicen rutinas de "conteo" para cerrar operaciones. Por ejemplo, no use algo como esto:
for (i = 0; i<t; i++)
{
if(OrderSelect(tik,SELECT_BY_TICKET)){
double prc = Oferta;
if (op = OP_SELL) prc = Ask;
CloseOrder(tik, OrderLots(), prc);
}
Si está usando múltiples órdenes, no cerrará la última orden. Utilice una rutina de "cuenta atrás". Aquí está mi discusión con los desarrolladores de Metaquotes cuando me topé con este irritante "bug".
http://www.metaquotes.net/forum/2018/Ok, ¿cómo debería ser esto? y ¿esta línea hará lo que quiero que haga?
if (prc == Bid && currentlong minorts):
Una sugerencia a todos los miembros, no usen rutinas de "cuenta arriba" para cerrar operaciones. Por ejemplo, no utilice algo como esto:
for (i = 0; i<t; i++)
{
if(OrderSelect(tik,SELECT_BY_TICKET)){
double prc = Oferta;
if (op = OP_SELL) prc = Ask;
CloseOrder(tik, OrderLots(), prc);
}
Si está usando múltiples órdenes, no cerrará la última orden. Utilice una rutina de "cuenta atrás". Aquí está mi discusión con los desarrolladores de Metaquotes cuando me topé por primera vez con este irritante "bug".
http://www.metaquotes.net/forum/2018/Ok, ¿cómo debería ser esto? y ¿esta línea hará lo que quiero que haga?
if (prc == Bid && currentlong minorts);
{
if(OrderSelect(tik,SELECT_BY_TICKET)){
double prc = Bid;
if (op == OP_SELL) prc = Ask;
if (prc == Bid && currentlong minorts);
CloseOrder(tik, OrderLots(), prc);Por favor, consulte el enlace publicado en mi mensaje anterior. Hay un código de ejemplo en ese enlace.
Por favor, consulte el enlace publicado en mi mensaje anterior. En ese enlace hay un código de ejemplo.
Veo esta línea de la muestra..
for(trade=OrdersTotal()-1;trade>=0;trade--){
si bien entiendo la idea de contar hacia atrás en lugar de contar hacia adelante
esto es contar dos lugares correctos?
{
int tik[30], t = 0;
for(int i =0;i<OrdersTotal();i++){//------counting forward error here
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
if(OrderSymbol()==Symbol() && MagicNum==OrderMagicNumber() && OrderType() == op){
tik[t] = OrderTicket(); t++;
}
}
}
for (i = 0; i<t; i++)//------counting forward error here
{
if(OrderSelect(tik,SELECT_BY_TICKET)){
double prc = Bid;
if (op == OP_SELL) prc = Ask;
CloseOrder(tik, OrderLots(), prc);
}
}
}Es que estoy confundido sobre cómo cambiarlos... sería...
for(int i =0;i>Total de pedidos();i--){
y
for (i = 0; i>t; i--)
Todavía estoy tratando de conseguir mi cerebro alrededor de la cosa crossback.
Lo que sigue es un ejemplo de una rutina de cierre simple y sin campanas y silbatos. Creo que el código es bastante sencillo para empezar a trabajar.
void CloseAll()
{
int trade;
for(trade=OrdersTotal()-1;trade>=0;trade--)
{
OrderSelect(trade,SELECT_BY_POS,MODE_TRADES);
if(OrderSymbol()!=Symbol())
continue;
if(OrderSymbol()==Symbol() && OrderMagicNumber()== MagicNum)
{
if(OrderType()==OP_BUY)
OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Blue);
if(OrderType()==OP_SELL)
OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Red);
}
}
}
El siguiente es un ejemplo de una rutina de cierre simple, sin ningún tipo de campanas y silbatos. Creo que el código es bastante sencillo para empezar a trabajar.
void CloseAll()
{
int trade;
for(trade=OrdersTotal()-1;trade>=0;trade--)
{
OrderSelect(trade,SELECT_BY_POS,MODE_TRADES);
if(OrderSymbol()!=Symbol())
continue;
if(OrderSymbol()==Symbol() && OrderMagicNumber()== MagicNum)
{
if(OrderType()==OP_BUY && currentlong > minorts)//---I want to close long positions when the ema's crossback down
OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Blue);
if(OrderType()==OP_SELL) && currentlong < minorts)//---I want to close short positions when the ema's crossback up
OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Red);
}
}
}
}
Ok plain vanilla, eso es más bien...
I get these errors when I paste this in...
'(' - function definition unexpected C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (85, 14)
'trade' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (88, 6)
'trade' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (88, 28)
'trade' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (88, 37)
'trade' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (90, 15)
'MagicNum' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (94, 54)
'Slippage' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (97, 46)
')' - unbalanced right parenthesis C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (99, 53)
'Slippage' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (100, 46)
')' - unbalanced right parenthesis C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (100, 58)
'}' - unbalanced parentheses C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (104, 1)
11 error(s), 0 warning(s)
[/PHP]
I don't know why it says 'trade' is an error it looks like trade is defined as an 'int'
ok whatever...so...let's see...
//+--------- settings may vary use at your own risk-----------------+
#include
//+--------------user inputs--------------------+
extern double Trendsetter = 250;
extern double Minortrendsetter = 150;
extern double LongEMA = 20;
extern double ShortEMA = 5;
extern double TrailingStop = 15;
extern double TrailingStopTrigger = 1;
extern double StopLoss = 186;
extern double TakeProfit = 250;
extern double Lots = 0.1;
extern double EquityStop = 9;
extern int Slippage = 3;
#define trade 0
#define MagicNum 0
//---- Custom "Channel-1" Indicator and Filter Parameters
extern int Hours=36;
extern color col=SkyBlue;
extern double TF = 60; //--which bar period for the custom indicator to use
extern double upperproximity = 30; //---disallows long orders within this proximity to resistance line
extern double lowerproximity = 30; //---disallows short orders within this proximity to the support line
//+-----------close based on not triggering trailing stop in allotted time----------------+
extern int MonitorInMinutes = 60; // minutes after open to check state of trade
extern int ThresholdMove = 11; // if after that time we don't have +'x' pips we will exit
extern int MinsMultiplier = 600; // multiplies the MonitorInMinutes to make minutes (if 'x'=60) into hours
//+----------------------end of allotted time user inputs-----------------------------+
//+-----------------------------end of user inputs----------------------------------+
//+------------------------------------------------------------------+
//| expert start function
//+------------------------------------------------------------------+
int start(){
CloseOrder();
int cnt, ticket;
if(Bars<100){
Print("bars less than 100");
return(0);
}
//+----------------------Get Moving Average(s) Data----------------------------------------+
double currentlong=iMA(NULL,0,LongEMA,0,MODE_EMA,PRICE_CLOSE,0);//--current period longEMA
double currentshort=iMA(NULL,0,ShortEMA,0,MODE_EMA,PRICE_CLOSE,0);//--current period shortEMA
double trendsetter=iMA(NULL,0,Trendsetter,0,MODE_EMA,PRICE_CLOSE,0);//--current period TrendsetterEMA
double minorts=iMA(NULL,0,Minortrendsetter,0,MODE_EMA,PRICE_CLOSE,0);//--current period MinortrendsetterEMA
double prevlong=iMA(NULL,0,LongEMA,0,MODE_EMA,PRICE_CLOSE,1);//--previous period longEMA
double prevshort=iMA(NULL,0,ShortEMA,0,MODE_EMA,PRICE_CLOSE,1);//--previous period shortEMA
double prevtrendsetter=iMA(NULL,0,Trendsetter,0,MODE_EMA,PRICE_CLOSE,1);//--previous period TrendsetterEMA
double prevminorts=iMA(NULL,0,Minortrendsetter,0,MODE_EMA,PRICE_CLOSE,1);//--previous period MinortrendsetterEMA
//+----------------------------end of Get Moving Average(s) Data-----------------------------+
//+--------------------channel filter---------------------------+
double resistance = iCustom(NULL,TF,"Channel-1",Hours,col,0,0);
double support = iCustom(NULL,TF,"Channel-1",Hours,col,2,0);
//+------------------- end channel filter------------------------+
//+---------Obnoxious money management code needs revision-----------------+
int total=OrdersTotal();
if(total<1){
if(AccountFreeMargin()<(1000*Lots)){
Print("We have no money. Free Margin = ", AccountFreeMargin());
return(0);
}
//+---------end of Obnoxious money management code-----------------+
//+---------------------------------------Order Entry--------------------------------------------+
//+---------enter long positions----------+
if (prevshortcurrentlong && currentshort>currentlong>Trendsetter && Ask > resistance - upperproximity*Point){ //---conditions to open long positions change as desired
ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-StopLoss*Point,Ask+TakeProfit*Point, NULL,16384,0,Green);
if(ticket>0){
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES )) Print("BUY order opened : ",OrderOpenPrice());
}
else Print("Error opening BUY order : ",GetLastError());
return(0);
}
//+---------enter short positions----------+
if (prevshort>prevlong && currentshort<currentlong && currentshort<currentlong<Trendsetter && Ask < support + lowerproximity*Point){ //---conditions to open short positions change as desired
ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Bid+StopLoss*Point,Bid-TakeProfit*Point, NULL,16384,0,Red);
if(ticket>0) {
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES )) Print("SELL order opened : ",OrderOpenPrice());
}
else Print("Error opening SELL order : ",GetLastError());
return(0);
}
}
//+---------end of order entry-------------------------+
//+------close on moving average cross-----------------+
void CloseAll()
{
int trade;
for(trade=OrdersTotal()-1;trade>=0;trade--)
{
OrderSelect(trade,SELECT_BY_POS,MODE_TRADES);
if(OrderSymbol()!=Symbol())
continue;
if(OrderSymbol()==Symbol() && OrderMagicNumber()== MagicNum)
{
if(OrderType()==OP_BUY && currentlong > minorts)//---I want to close long positions when the ema's crossback down
OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Blue);
if(OrderType()==OP_SELL && currentlong < minorts)//---I want to close short positions when the ema's crossback up
OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Red);
}
}
}
}
//+--------end of close on moving average cross--------+now by adding this
extern int Slippage = 3;
#define trade 0
#define MagicNum 0
I'm down to...
[PHP]Compiling 'whatever.mq4'...
'(' - function definition unexpected C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (87, 14)
'}' - unbalanced parentheses C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (106, 1)
2 error(s), 0 warning(s)
I don't know what to do about these two.
[PHP]//+------close on moving average cross-----------------+
void CloseAll()//function definition unexpected error occurs here
{
int trade;
for(trade=OrdersTotal()-1;trade>=0;trade--)
{
OrderSelect(trade,SELECT_BY_POS,MODE_TRADES);
if(OrderSymbol()!=Symbol())
continue;
if(OrderSymbol()==Symbol() && OrderMagicNumber()== MagicNum)
{
if(OrderType()==OP_BUY && currentlong > minorts)//---I want to close long positions when the ema's crossback down
OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Blue);
if(OrderType()==OP_SELL && currentlong < minorts)//---I want to close short positions when the ema's crossback up
OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Red);
}
}
}
}//--------unblanced parentheses error occurs here
¿Dónde has definido la función"CloseOrder(); "? El nombre de la función de cierre que publiqué era diferente... CloseAll()
A ver si así se solucionan los problemas.
Ok, eso tiene sentido...así que supongo que hay estrategias de cierre que compiten aquí...el CloseOrder() estaba relacionado con el cierre a tiempo en la función de comercio que nunca he trabajado para hacer lo que pretendía. Así que supongo que por el momento y para el propósito actual que acaba de eliminar que eh ... alguien me mostró un truco fresco para desactivar el código sólo tiene que añadir el "//" a la parte delantera de la línea ...
aqui esta todo....as es..
//+--------- settings may vary use at your own risk-----------------+
#include
//+--------------user inputs--------------------+
extern double Trendsetter = 250;
extern double Minortrendsetter = 150;
extern double LongEMA = 20;
extern double ShortEMA = 5;
extern double TrailingStop = 15;
extern double TrailingStopTrigger = 1;
extern double StopLoss = 186;
extern double TakeProfit = 250;
extern double Lots = 0.1;
extern double EquityStop = 9;
extern int Slippage = 3;
#define trade 0
#define MagicNum 0
//---- Custom "Channel-1" Indicator and Filter Parameters
extern int Hours=36;
extern color col=SkyBlue;
extern double TF = 60; //--which bar period for the custom indicator to use
extern double upperproximity = 30; //---disallows long orders within this proximity to resistance line
extern double lowerproximity = 30; //---disallows short orders within this proximity to the support line
//+-----------close based on not triggering trailing stop in allotted time----------------+
extern int MonitorInMinutes = 60; // minutes after open to check state of trade
extern int ThresholdMove = 11; // if after that time we don't have +'x' pips we will exit
extern int MinsMultiplier = 600; // multiplies the MonitorInMinutes to make minutes (if 'x'=60) into hours
//+----------------------end of allotted time user inputs-----------------------------+
//+-----------------------------end of user inputs----------------------------------+
//+------------------------------------------------------------------+
//| expert start function
//+------------------------------------------------------------------+
int start(){
//+--turned off--+CloseOrder();
int cnt, ticket;
if(Bars<100){
Print("bars less than 100");
return(0);
}
//+----------------------Get Moving Average(s) Data----------------------------------------+
double currentlong=iMA(NULL,0,LongEMA,0,MODE_EMA,PRICE_CLOSE,0);//--current period longEMA
double currentshort=iMA(NULL,0,ShortEMA,0,MODE_EMA,PRICE_CLOSE,0);//--current period shortEMA
double trendsetter=iMA(NULL,0,Trendsetter,0,MODE_EMA,PRICE_CLOSE,0);//--current period TrendsetterEMA
double minorts=iMA(NULL,0,Minortrendsetter,0,MODE_EMA,PRICE_CLOSE,0);//--current period MinortrendsetterEMA
double prevlong=iMA(NULL,0,LongEMA,0,MODE_EMA,PRICE_CLOSE,1);//--previous period longEMA
double prevshort=iMA(NULL,0,ShortEMA,0,MODE_EMA,PRICE_CLOSE,1);//--previous period shortEMA
double prevtrendsetter=iMA(NULL,0,Trendsetter,0,MODE_EMA,PRICE_CLOSE,1);//--previous period TrendsetterEMA
double prevminorts=iMA(NULL,0,Minortrendsetter,0,MODE_EMA,PRICE_CLOSE,1);//--previous period MinortrendsetterEMA
//+----------------------------end of Get Moving Average(s) Data-----------------------------+
//+--------------------channel filter---------------------------+
double resistance = iCustom(NULL,TF,"Channel-1",Hours,col,0,0);
double support = iCustom(NULL,TF,"Channel-1",Hours,col,2,0);
//+------------------- end channel filter------------------------+
//+---------Obnoxious money management code needs revision-----------------+
int total=OrdersTotal();
if(total<1){
if(AccountFreeMargin()<(1000*Lots)){
Print("We have no money. Free Margin = ", AccountFreeMargin());
return(0);
}
//+---------end of Obnoxious money management code-----------------+
//+---------------------------------------Order Entry--------------------------------------------+
//+---------enter long positions----------+
if (prevshortcurrentlong && currentshort>currentlong>Trendsetter && Ask > resistance - upperproximity*Point){ //---conditions to open long positions change as desired
ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-StopLoss*Point,Ask+TakeProfit*Point, NULL,16384,0,Green);
if(ticket>0){
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES )) Print("BUY order opened : ",OrderOpenPrice());
}
else Print("Error opening BUY order : ",GetLastError());
return(0);
}
//+---------enter short positions----------+
if (prevshort>prevlong && currentshort<currentlong && currentshort<currentlong<Trendsetter && Ask < support + lowerproximity*Point){ //---conditions to open short positions change as desired
ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Bid+StopLoss*Point,Bid-TakeProfit*Point, NULL,16384,0,Red);
if(ticket>0) {
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES )) Print("SELL order opened : ",OrderOpenPrice());
}
else Print("Error opening SELL order : ",GetLastError());
return(0);
}
}
//+---------end of order entry-------------------------+
//+------close on moving average cross-----------------+
void CloseAll()//function definition unexpected error occurs here
{
int trade;
for(trade=OrdersTotal()-1;trade>=0;trade--)
{
OrderSelect(trade,SELECT_BY_POS,MODE_TRADES);
if(OrderSymbol()!=Symbol())
continue;
if(OrderSymbol()==Symbol() && OrderMagicNumber()== MagicNum)
{
if(OrderType()==OP_BUY && currentlong > minorts)//---I want to close long positions when the ema's crossback down
OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Blue);
if(OrderType()==OP_SELL && currentlong < minorts)//---I want to close short positions when the ema's crossback up
OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Red);
}
}
}
}//--------unblanced parentheses error occurs here
//+--------end of close on moving average cross--------+
//+-------------------------Trailing Stop Code------------------------------------+
for(cnt=0;cnt<total;cnt++) {
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()<=OP_SELL && OrderSymbol()==Symbol()) {
if(OrderType()==OP_BUY){
if(TrailingStop>0) {if(Bid-OrderOpenPrice()>Point*TrailingStopTrigger) {
if(OrderStopLoss()<Bid-Point*TrailingStop) {
OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TrailingStop,OrderTakeProfit(),0,Green);
return(0);
}
}
}
}else{
if(TrailingStop>0) {if((OrderOpenPrice()-Ask)>(Point*TrailingStopTrigger)) {
if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0)) {
OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,OrderTakeProfit(),0,Red);
return(0);
}
}
}
}
//+-------------------------End of Trailing Stop Code----------------------------+
//+---------------------Equity Stop Code---------------------------+
if((AccountEquity()+ EquityStop)<AccountBalance()) {
{
int ttotal = OrdersTotal();
for(int i=ttotal-1;i>=0;i--)
{
OrderSelect(i, SELECT_BY_POS);
int type = OrderType();
bool result = false;
switch(type)
{
//Close opened long positions
case OP_BUY : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );
break;
//Close opened short positions
case OP_SELL : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );
}
if(result == false)
{
Alert("Order " , OrderTicket() , " failed to close. Error:" , GetLastError() );
Sleep(3000);
}
}
return(0);
}
}
}
}
}
//+---------------------End of Equity Stop Code---------------------------+
//|
//+---------------------Close Based on Time-------------------------------+
//+--------------needs revision, not working as desired---------------------+
//+------------I want it to close IF and ONLY IF trailing stop is NOT triggered-------------+
//+--turned off--+void CloseOrder()
//+--turned off--+{
//+--turned off--+ double Profit=ThresholdMove*Point;
//+--turned off--+ int total = OrdersTotal();
//+--turned off--+ for (int cnt = 0 ; cnt < total ; cnt++)
//+--turned off--+ {
//+--turned off--+ OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
//+--turned off--+ if ((CurTime()-OrderOpenTime())>MonitorInMinutes*60*MinsMultiplier)
//+--turned off--+ {
//+--turned off--+ if(OrderSymbol()==Symbol() && OrderType()==OP_BUY && Bid-Profit<OrderOpenPrice() )
//+--turned off--+ {
//+--turned off--+ OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet);
//+--turned off--+ }
//+--turned off--+ if(OrderSymbol()==Symbol() && OrderType()==OP_SELL && Bid+Profit>OrderOpenPrice())
//+--turned off--+ {
//+--turned off--+ OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet);
//+--turned off--+ }
//+--turned off--+ }
//+--turned off--+ }
//+--turned off--+}
//+---------------------------end of close on time code---------------+los mismos dos errores siguen ocurriendo al compilar.
Bien, todavía estoy esperando que me llegue un correo electrónico. Así que... unos minutos más para matar.
Tienes que cortar la función closeall y pegarla fuera del bucle de inicio. Es una función separada. Luego tienes que llamar a la función closeall desde el bucle de inicio donde quieres que cierre las operaciones. Creo que tienes que estudiar este concepto de llamar a las funciones antes de ir más allá.
Vale, todavía estoy esperando que me llegue un correo electrónico. Así que... unos minutos más para matar. Tienes que cortar la función closeall y pegarla fuera del bucle de inicio. Es una función separada. Luego tienes que llamar a la función closeall desde el bucle de inicio donde quieres que cierre las operaciones. Creo que tienes que estudiar este concepto de llamar a las funciones antes de ir más allá.
hasta ahora por lo que puedo ver en el editor sobre las funciones está buscando parámetros y no veo ninguno especificado en el ()?
..dices que tengo que 'cortar' y 'pegar fuera del bucle de inicio'
//| expert start function
//+------------------------------------------------------------------+
CloseAll();
int start(){
//+--turned off--+CloseOrder(); [/PHP]
this gives the same two errors plus this error
'CloseAll' - expression on global scope not allowed C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (33, 1)
when I put it next to where the other one was like this...
[PHP]int start(){
//+--turned off--+CloseOrder();
CloseAll();eso sigue dejando los dos errores abajo de la página como si no hubiera ninguna diferencia. Tienes razón no entiendo nada de esto de la llamada a la función.
¿sabes cómo hacer que esto funcione?
Estoy mirando aquí http://www.metatrader.info/node/53 de refilón no veo qué es lo que falla.