Ajuda na codificação... Como obter um indicador para filtrar em vez de alertar? - página 8

 

U da man!

so....let's veja se entendi corretamente...

se eu quisesse fechar posições com base na cruz traseira de uma média móvel tudo o que eu precisaria codificar era esta....

if(currentlong>minorts) {CloseOrder(OP_SELL); // Fechar todas as ordens de venda}

onde a corrente é o 20ema e os minorts é o 150ema, então a posição aberta teria sido ou é uma posição curta, que tem corrido seu curso e agora o 20ema está se movendo acima do 150ema, que é o sinal de fechamento para o comércio curto.

e...

se (currentlong<minorts) {CloseOrder(OP_BUY); // Fechar todas as ordens de compra}

onde a corrente é o 20ema e os minorts é o 150ema, então a posição aberta teria sido ou É um longo curso e agora o 20ema está se movendo abaixo do 150ema, que é o sinal de fechamento para o longo comércio.

Então eu poderia simplesmente colocar estas duas linhas

if (currentlong<minorts) {CloseOrder(OP_BUY); // Fechar todas as ordens de compra}

if(currentlong>minorts) {CloseOrder(OP_SELL); // Fechar todas as ordens de venda}

logo após o código de entrada e antes de todas as outras paradas de fechamento e rastreamento como esta? e vai funcionar?

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-----------------+

if(currentlong<minorts) {CloseOrder(OP_BUY);} // Close all buy orders}

if(currentlong>minorts) {CloseOrder(OP_SELL);} // Close all sell orders}

//+--------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){

o compilador diz isto:

")" - parâmetros errados contamC: Arquivos de programa Interbank FX Trader 4-live mini-peritos em qualquer coisa.mq4 (85, 43)

")" - parâmetros errados contamC: Arquivos de programas Interbank FX Trader 4-live mini-peritos em qualquer coisa.mq4 (86, 44)

não gosta dessas linhas. Não sinto que estou me comunicando muito bem.

 

isto é interessante de repente minha função de busca no metaeditor funciona??

bool OrderCloseBy( int ticket, int oposto, cor=CLR_NONE)

Encerra uma ordem aberta por outra ordem aberta em sentido contrário. Se a função for bem sucedida, o valor de retorno é verdadeiro. Se a função falhar, o valor de retorno é falso. Para obter a informação detalhada do erro, ligue para GetLastError().

Parâmetros:

ticket - Número único do ticket de pedido.

oposto - Número único do bilhete de pedido oposto.

Cor - Cor da seta de fechamento na tabela. Se o parâmetro estiver faltando ou tiver CLR_NONE a seta de fechamento do valor não será desenhada no gráfico.

Amostra:

if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75)

{

OrderCloseBy(order_id,opposite_id);

return(0);

}

então estou visualizando algo como isto...

if(currentlong<minorts)

{

OrderCloseBy(order_id,opposite_id);

return(0);

}[/PHP]

thing is this doesn't distinguish what kind of position I'm into first, long or short. So if I put the opposite side of this with it...like this...

[PHP] if(currentlong>minorts)

{

OrderCloseBy(order_id,opposite_id);

return(0);

}

juntos eles simplesmente fechariam tudo, não é mesmo? tem que haver mais... Sinto-me tão frustrado como uma criança que ainda não consegue falar para comunicar sentenças completas, quando tenho idéias completas dentro de mim que não consigo tirar.

 
elihayun:
Esqueço este aqui
void CloseOrder(int ticket,double numLots,double close_price)

{

int CloseCnt, err;

// try to close 3 Times

CloseCnt = 0;

color clr = Violet;

if (OrderType() == OP_SELL)

clr = Orange;

while (CloseCnt < 3)

{

if (OrderClose(ticket,numLots,close_price,Slippage,clr))

{

CloseCnt = 3;

}

else

{

err=GetLastError();

Print(CloseCnt," Error closing order : (", err , ") " + ErrorDescription(err));

if (err > 0) CloseCnt++;

}

}

}

[/PHP]

and dont forget to add this line after #property link

[PHP]#property link "http://www.elihayun.com"

#include

o que isso faz? é algo mais que eu tenho que baixar para que esteja disponível para ser chamado? Quero entender como isto faz o que faz, como distingue as posições longas das curtas. Eu quero aprender.

 
Aaragorn:
U da man!

so....let's veja se entendi corretamente...

Então eu poderia apenas colocar estas duas linhas

if (currentlong<minorts) {CloseOrder(OP_BUY); // Fechar todas as ordens de compra}

if(currentlong>minorts) {CloseOrder(OP_SELL); // Fechar todas as ordens de venda}

//+------close on moving average cross-----------------+

if(currentlong<minorts) {CloseOrder(OP_BUY);} // Fechar todas as ordens de compra}

if(currentlong>minorts) {CloseOrder(OP_SELL);} // Fechar todas as ordens de venda}

if(OrderType()==OP_BUY){[/PHP]

o compilador diz o seguinte:

')' - parâmetros errados contamC: Arquivos de programa Interbank FX Trader 4-live mini-peritos em qualquer coisa.mq4 (85, 43)

")" - parâmetros errados contamC: Arquivos de programas Interbank FX Trader 4-live mini-peritos em qualquer coisa.mq4 (86, 44)

não gosta dessas linhas. Não sinto que estou me comunicando muito bem.

Você tem que ligar para CloseOrders com s no final e não CloseOrder (que fecha apenas um pedido)

 
Aaragorn:
o que isso faz? é algo mais que eu tenho que baixar para que esteja disponível para ser chamado? Quero entender como isto faz o que faz, como distingue as posições longas das curtas. Eu quero aprender.

Sua parte da MQL4 e contém a função ErrorDescription

 
elihayun:
Sua parte da MQL4 e contém a função ErrorDescription

ok Eu ainda preciso de algum código que me permita fechar com base na média móvel de retorno.

 

Este pedaço de código deve te levar...

É claro que você terá que modificá-lo para se adequar às suas próprias necessidades. No entanto, isto deve lhe proporcionar um ponto de partida. Esta rotina usa a linha SMA1 como ponto de partida. Portanto, pegue esta idéia e veja o que você pode fazer com ela.

//these two lines within start()

SMA1 = iMA(NULL,TimePeriod,SlowPeriod,0,SlowMode,SlowPrice,1);

TrailingAlls(TrailStart, SMA1);

// trailing routine using the value of SMA1

void TrailingAlls(int start, double currvalue)

{

int profit;

double stoptrade;

double stopcal;

// if(stop==0) return;

int trade;

for(trade=OrdersTotal()-1;trade>=0;trade--)

{

if(!OrderSelect(trade,SELECT_BY_POS,MODE_TRADES))

continue;

if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)

continue;

if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)

{

if(OrderType()==OP_BUY)

{

profit=NormalizeDouble((Bid-OrderOpenPrice())/Point,0);

if(profit<start)

continue;

stoptrade=OrderStopLoss();

// stopcal=Bid-(stop*Point);

stopcal=NormalizeDouble(currvalue, Digits);

if(stoptrade==0||(stoptrade!=0&&stopcal>stoptrade))

OrderModify(OrderTicket(),OrderOpenPrice(),stopcal,OrderTakeProfit(),0,Blue);

}//Long

if(OrderType()==OP_SELL)

{

profit=NormalizeDouble((OrderOpenPrice()-Ask)/Point,0);

if(profit<start)

continue;

stoptrade=OrderStopLoss();

// stopcal=Ask+(stop*Point);

stopcal=NormalizeDouble(currvalue, Digits);

if(stoptrade==0||(stoptrade!=0&&stopcal<stoptrade))

OrderModify(OrderTicket(),OrderOpenPrice(),stopcal,OrderTakeProfit(),0,Red);

}//Shrt

}

}//for

}

 

uma parada de reboque próxima é possivelmente útil se eu puder descobrir isso primeiro....

este trecho que elihayun me deu, acho que poderia funcionar se alguém conseguisse descobrir como fazer com que ele respondesse ao backcross e na direção certa. Estou confuso com o op_buy e op_sell que é qual. e qual usar para fechar posições longas e qual usar para fechar posições curtas.

//+------close on moving average cross-----------------+

void CloseOrders(int op)

{

int tik[30], t = 0;

for(int i =0;i<OrdersTotal();i++){

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++)

{

if(OrderSelect(tik,SELECT_BY_TICKET)){

double prc = Bid;

if (op == OP_SELL) prc = Ask;

CloseOrder(tik, OrderLots(), prc);

}

}

}

//+--------end of close on moving average cross--------+[/PHP]

I think I see that at this point in the code it has selected the orders by ticket and it's figuring out to set the close price based on the bid or the ask. So I'm not sure which is which for long or short positions. If the ticket is a long position that means it was opened at the ask price right? so it should close on the bid price? so this snippet is saying use the bid price to close so I assume that's for a long position. THEN it asks the

if (op == OP_SELL) prc = Ask;

so I assume this is the first place in this code where we now know if we are looking at a long or a short position ticket.

Then it moves immediately to close. But if I can put my closing criteria in here BEFORE it does that???

here it is as I received it...

for (i = 0; i<t; i++)

{

if(OrderSelect(tik,SELECT_BY_TICKET)){

double prc = Bid;

if (op == OP_SELL) prc = Ask;

CloseOrder(tik, OrderLots(), prc);

}[/PHP]

so what I'm thinking is that this is the place in the code where I should insert the moving average criteria to trigger the close for long or short positions. Something like this...

[PHP]for (i = 0; i<t; i++)

{

if(OrderSelect(tik,SELECT_BY_TICKET)){

double prc = Bid;

if (op == OP_SELL) prc = Ask;

if (prc == Bid && currentlong minorts);

CloseOrder(tik, OrderLots(), prc);

}

Will this do it? I think it might if I understand correctly..

Please tell me coders if this is correct??

I think this connects the direction of the moving average cross to the type of position that the ticket is identifed as being.

if the bid is to close long positions so we know the ticket is for a long position then it can close long positions if the currentlongema < minortsEMA because it knows that the ticket is for a long position and the 20ema has moved below the 150ema.

If the ask is for closing short positions and the ticket is identified as a short position because it wants to close at the ask price and the currentlongEMA has moved above the minortsEMA because it knows the ticket is for a short position and the 20ema has moved above the 150ema.

if that is correct will adding this line to the code,

if (prc == Bid && currentlong minorts)

stop it from closing UNLESS each ticket fits this criteria?

...that for the long position the 20ema150ema?

if that is ok then the logic for deciding to close long or short based on the emacrossback is ok and it's worth fixing these errors

I get these errors from the compiler...

[PHP]Compiling 'whatever.mq4'...

'(' - function definition unexpected C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (85, 17)

'MagicNum' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (90, 40)

'op' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (90, 87)

'tik' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (91, 13)

't' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (91, 17)

't' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (91, 37)

't' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (96, 18)

'tik' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (98, 22)

'op' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (100, 14)

'tik' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (102, 21)

'cnt' - expression on global scope not allowed C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (108, 5)

'cnt' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (108, 5)

'cnt' - expression on global scope not allowed C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (108, 11)

'cnt' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (108, 11)

'total' - expression on global scope not allowed C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (108, 15)

'total' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (108, 15)

'cnt' - expression on global scope not allowed C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (108, 21)

'cnt' - variable not defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (108, 21)

'{' - expression on global scope not allowed C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (108, 28)

'i' - variable is already defined C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (135, 11)

'}' - unbalanced parentheses C:\Program Files\Interbank FX Trader 4-live mini\experts\whatever.mq4 (165, 1)

16 error(s), 5 warning(s)

 

Uma sugestão para todos os membros, não utilizar rotinas de "contagem regressiva" para fechar negócios. Por exemplo, não utilize algo assim:

para (i = 0; i<t; i++)

{

if(OrderSelect(tik,SELECT_BY_TICKET)){

duplo prc = Licitação;

se (op == OP_SELL) prc = Perguntar;

CloseOrder(tik, OrderLots(), prc);

}

Se você estiver usando vários pedidos, não fechará o último pedido. Use uma rotina de "contagem regressiva". Aqui está minha discussão com os desenvolvedores de Metaquotes quando tropeçei pela primeira vez neste irritante "bug".

http://www.metaquotes.net/forum/2018/

 
Maji:
Este pedaço de código deve fazer com que você vá...

É claro que você terá que modificá-lo para atender às suas próprias necessidades. No entanto, isto deve lhe proporcionar um ponto de partida. Esta rotina usa a linha SMA1 como ponto de partida. Portanto, pegue esta idéia e veja o que você pode fazer com ela.

//these two lines within start()

SMA1 = iMA(NULL,TimePeriod,SlowPeriod,0,SlowMode,SlowPrice,1);

TrailingAlls(TrailStart, SMA1);

// trailing routine using the value of SMA1

void TrailingAlls(int start, double currvalue)

{

int profit;

double stoptrade;

double stopcal;

// if(stop==0) return;

int trade;

for(trade=OrdersTotal()-1;trade>=0;trade--)

{

if(!OrderSelect(trade,SELECT_BY_POS,MODE_TRADES))

continue;

if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)

continue;

if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)

{

if(OrderType()==OP_BUY)

{

profit=NormalizeDouble((Bid-OrderOpenPrice())/Point,0);

if(profit<start)

continue;

stoptrade=OrderStopLoss();

// stopcal=Bid-(stop*Point);

stopcal=NormalizeDouble(currvalue, Digits);

if(stoptrade==0||(stoptrade!=0&&stopcal>stoptrade))

OrderModify(OrderTicket(),OrderOpenPrice(),stopcal,OrderTakeProfit(),0,Blue);

}//Long

if(OrderType()==OP_SELL)

{

profit=NormalizeDouble((OrderOpenPrice()-Ask)/Point,0);

if(profit<start)

continue;

stoptrade=OrderStopLoss();

// stopcal=Ask+(stop*Point);

stopcal=NormalizeDouble(currvalue, Digits);

if(stoptrade==0||(stoptrade!=0&&stopcal<stoptrade))

OrderModify(OrderTicket(),OrderOpenPrice(),stopcal,OrderTakeProfit(),0,Red);

}//Shrt

}

}//for

}

Muito obrigado. Estou ansioso para dissecar isto e ver o que posso fazer com isto.

a razão pela qual eu quero fazer o emacrossback funcionar primeiro é que ele será basicamente meu stoploss e minha estratégia de saída padrão.

Uma vez que isso esteja funcionando, então acrescentarei coisas como esta para aumentar a lucratividade. Mas como não posso ter um stop loss sem estragar tudo e como não estou disposto a permitir parâmetros de stop loss enormes, quero fazer com que o crossback de fechamento médio móvel funcione primeiro. Se você tiver a oportunidade de verificar o que fiz até agora com o fechamento de crossback, eu gostaria muito.

Razão: