Moving Average Ordersend Error 131


EA atualizada, Backtesting, erros comuns e algum código de trabalho Inscrito em Jul 2008 Status: Membro 62 Posts Este tópico pode ser de interesse para aqueles de vocês que querem começar ou já começaram a desenvolver seu próprio Expert Advisor personalizado. Este não é um quotMetaTrader 4 MQL Expert Advisor Tutorialquot ou algo assim, mas pode ser de ajuda para iniciantes, impede de cometer alguns erros e fornecer código de trabalho para algumas das funções mais comuns. Há alguns meses, escrevi minha primeira EA, muito simples, apenas para fins de aprendizagem e postei-a neste tópico. Eu tentei mantê-lo o mais simples possível e forneci muitos comentários para tornar mais fácil para os iniciantes seguir a estratégia da minha EA e como a implementei. Durante as últimas semanas, leio muito sobre análises de gráficos, análise inter-mercado e previsão de preços com redes neurais. Além disso, desenvolvi algumas bibliotecas que contêm funcionalidades muitas vezes necessárias, como gerenciamento de dinheiro, gerenciamento de pedidos, gerenciamento de erros e registro de erros. E eu também aprendi muito sobre os testes de backtesting, validação e ajuste de curva. Erro de backtesting comum que eu fiz no começo E isso já é o ponto que não era realmente inteligente com minha última abordagem: otimizei a EA por um determinado período e, em seguida, testei a EA para o mesmo período. Não faça isso E se você fizer isso - não tome esses resultados e acredite que você encontrou o último Holy-Grail-EA Queremos desenvolver uma EA que não só crie curvas de equidade agradáveis ​​para o nosso período otimizado (quot curve fitting quot) Mas também para o futuro. Imagem, queremos escrever uma EA que use o gráfico diário como período de tempo e temos os seguintes dados da série temporal disponíveis: agora fazemos backtesting e otimização da EA. Isso significa que determinamos as médias móveis, o risco, o tamanho da parada final (ou quaisquer variáveis ​​que usamos em nossa EA) que resulte no saldo mais alto (redução menor, recompensa esperada). Se fizermos isso durante todo o período de 2003 a 2008, podemos obter uma curva muito boa, mas não temos idéia de como a EA realizaria em 2009. Uma boa solução, seja o que devemos aos dados da série temporal em duas partes: Um para otimização e uma parte para o teste de validação: agora seria uma otimização para 2003-2005 e usamos esses valores para testar em 2006. Se ainda obtivermos bons resultados, nossa EA teria sido bem sucedida no futuro, embora nós o testássemos para o passado. Como a EA não foi otimizada para o ano de 2006. Podemos repetir isso nos próximos anos e tentar encontrar essas configurações, que produziram bons resultados para todos ou a maioria dos períodos. Não sei qual período você deve escolher para otimizar e para testar. Este é um teste e erro e também depende do prazo em que você escolhe para permitir que seu EA funcione. Obtendo melhor qualidade de modelagem Quanto mais dados você tiver, melhor (significa mais exatamente) os resultados de backtesting serão. Esta é uma maneira de melhorar a qualidade de modelagem: no menu de opções do MetaTrader 4 (pressione CtrlO) selecione a guia quotChartsquot e defina esses valores para quotMax barras no historyquot e quotMax barras em chartquot: 2147483647 - clique em OK. Em seguida, abra o Centro de História em MT4 (pressione F2), selecione o par de moedas na lista de símbolos à esquerda e selecione o prazo mais baixo, 1 minuto (clique duas vezes). Pressione quotDownloadquot e responda quotOKquot quando você receber o aviso. Pode levar alguns minutos até que todo o valor histórico tenha sido baixado. Eu tenho velas de 3,5 minutos de Mio de 1 minuto, ou seja, os últimos 10 anos em minutos devem ser suficientes. Você pode fazer isso com cada período de tempo e moeda, ou usar o script quotperiodconverterquot incluído, que vem com o MT4. Em seguida, fornecerei algumas bibliotecas que escrevi e que me ajudem a não reescrever cada pouco que eu costumo precisar. Eu salve todos os pedidos abertos em uma matriz (apenas aqueles pedidos que a EA abriu de cortesia) para que eu pudesse ver quantos pedidos foram abertos no total. E escrevi uma pequena função que simplifica a abertura de uma posição. Definir MAGICNUMBER 29031985 Máximo de deslizamento permitido para execução de ordem definir SLIPAGE 5 Salvar todas as ordens abertas nesta matriz int Ticket 9193 Contar posições abertas para uma determinada moeda e salvar nossos pedidos na matriz de tickets. Não podemos simplesmente retornar ArraySize (Ticket), porque algumas ordens já poderiam ter sido interrompidas. Int countOpenOrders () return (updateOrderManager ()) Abre uma nova posição e retorna o par de par de par de parâmetros do código de erro, use o comando param de EURUSD ou Symbol () VENDER ou VENDER - não use OPBUY ou OPSELL param lot tamanho de ordem em lot param stoploss Stoploss param takeprofit takeprofit int newMarketOrder (par de cordas, comando de seqüência, duplo, duplo, stoploss, duplo takeprofit) Comando de compra, envie se (comando COMPRAR comando comprar) retornar (OrderSend (par. OPBUY. Lot. Ask. SLIPAGE. Stoploss. Takeprofit. . MAGICNUMBER. 0. Green)) Vender comando enviar else if (comando VENDER comando vender) return (OrderSend (par. OPSELL. Lot. Bid. SLIPAGE. Stoploss. Takeprofit ... MAGICNUMBER. 0. Red)) else return (- 2 ) Atualiza todas as informações sobre os pedidos abertos no momento. Especialmente olha através de todos os pedidos se eles ainda estão ativos ou talvez tenham sido impedidos por parar de perdas e salve seu número de ticket na matriz do Ticket. Int updateOrderManager () int count 0 Redimensionar matriz de tickets para zero ArrayResize (Ticket. 0) Ir para todas as ordens de (int i 0 i lt OrdersTotal () i) Foram apenas interessados ​​em negócios que estão no pool comercial As ordens fechadas ou canceladas são Não é interessante para nós se (OrderSelect (i. SELECTBYPOS. MODETRADES) false) break Contagem de posições que foram abertas pela nossa EA se ((OrderMagicNumber () MAGICNUMBER)) Redimensionar matriz de tickets e salvar ticket ArrayResize (Contagem de Bilhete 1) Contagem de Bilhete 91 93 OrderTicket () Retornar retorno de posições abertas (contagem) Bilhete - armazena todos os números de ticket das ordens de abertura atualizadas do current. OrderManager () - deve ser chamado de todos os carrapatos ou antes de querer usar o Ticket, porque poderia ter sido que um pedido foi feito Clamaram. Isso atualiza as atualizações do conjunto de itens de TicketOpenOrders () - conta o número de ordens abertas, simplesmente um subproduto da função mencionada anteriormente newMarketOrder (par de strings, comando de string, lote duplo, duplo stoploss, takeprofit duplo) - torna mais fácil para mim abrir Uma nova ordem. Par pode ser quotEURUSD por exemplo ou use Symbol () para usar o símbolo atual do gráfico anexado. O comando é quotBUYquot ou quotSELLquot, lot, stoploss e takeprofit são auto-explicativos. O deslizamento é definido no início do código, apenas as ordens de mercado são possíveis. Mas não há problema em escrever uma função newPendingOrder. Esta é uma biblioteca muito simples que pode ser usada para calcular a margem, a equidade, o saldo e o lucro atuais e usados ​​atuais. Mais importante é a função de calcular o tamanho ótimo do lote para um determinado risco e parar a perda. Variáveis ​​Externas externo duplo Risco 0,02 duplo saldo 0,00 dobro equidade 0,00 margem duplaFree 0,00 margem duplaUsada 0,00 margem duplaMercado igual 0,00 margem duplaPessoal Usável 0,00 dupla lucroPasse de Perigo 0,00 Calcule o tamanho ótimo do lote Se o sl foi definido, calcule o tamanho do lote de acordo com a perda de parada, use o risco de margem Como tamanho do lote Parâmetro: sl, Stop Loss in Point-Value (por exemplo, 0.0050 50 pips) lotes duplosOptimizados (dupla folga) lotes duplos Coloque o risco nos limites corretos se (Risco lt 0.001) Risco 0.001 se (Risco gt 0.50) Risco 0.50 dupla alavancagem MarketInfo (Symbol (), MODELOTSIZE) MarketInfo (Symbol (), MODEMARGINREQUIRED) Calcule a margem usada de acordo com o risco se a perda de parada for muito pequena se ((stoploss lt MarketInfo (Symbol (), MODESTOPLEVEL)) ampamp (stoploss gt 0)) lotes AccountEquity () Alavancagem do risco MarketInfo (Symbol (), MODELOTSIZE) Calcule o lote, de modo que somente o risco de equidade pode ser perdido. S para valores de pips se o stoploss negativo, torná-lo positivo se (stoploss lt 0) stoploss - stoploss MarketInfo (Symbol (), MODEPOINT) else stoploss stoploss MarketInfo (Symbol (), MODEPOINT) Calcule o valor de um pip por lote duplo PipValuePerLot MarketInfo (Symbol (), MODELOTSIZE) MarketInfo (Symbol (), MODEPOINT) Calcule o valor necessário por pip para arriscar o valor correto do capital de acordo com o tamanho Sl Double NeededPipValue AccountEquity () Risk scplass Calcule o tamanho ótimo do lote lotes NeededPipValue PipValuePerLot Verifique se o tamanho do lote Está em limites corretos se (lotes lt MarketInfo (Symbol (), MODEMINLOT)) lotes MarketInfo (Symbol (), MODEMINLOT) else if (lotes gt MarketInfo (Symbol (), MODEMAXLOT)) lotes MarketInfo (Symbol (), MODEMAXLOT) Recalcula Livre livre, margem usada e outros valores de atualização duplaMoneyManager () saldo AccountBalance () equity AccountEquity () margemFree AccountFreeMargin () margemUsed equity - marginFree marg InUsedPercent marginUsed equity 100 marginUsablePercent marginFree equity 100 profitLossPercentage AccountProfit () saldo 100 updateMoneyManager () - recalcula a atual margem gratuita e usada, economiza patrimônio, saldo e lucro nas variáveis. LotsOptimized (double stoploss) - calcula o tamanho ótimo do lote para uma ordem sob o risco dado e perda de stop. O risco é definido no início do arquivo: 0,02 significa: não arrisca mais de 2 do valor total do patrimônio líquido. Equidade da conta 10.000 Risco 0.02 2 Parar a perda em EURUSD é fixado para 0.0100 100 Pips Nós arrisamos apenas 2 de 10.000 200 Valor de pip por lote: 100.000 x 0.0001 10 Perda de parada 100 Pips, significa que queremos um valor de pip por lote de 200 100 2 Isso significa muito tamanho de 2 10 0,2 Se nós ficarmos parado agora com uma perda de 100 pip, nós só perdemos 200 ou 2. Simples. Se não for dada parada, o tamanho da posição será calculado de acordo com a quantidade de capital, risco e alavancagem. Esta não é, de longe, uma biblioteca de gerenciamento de dinheiro finalizada. É apenas uma base que pode e deve ser expandida. Algumas idéias: Defina um limite do capital máximo investido em porcentagem, como 2 por posição E não mais do que (por exemplo) 10 a 20 investidos em conjunto. Salve o saldo, patrimônio e curva de lucro em uma matriz. Em seguida, use esses dados para ver se os últimos negócios foram lucrativos ou não. Pode ser usado para o modo quotpanico ou para reduzir o risco quando os últimos negócios produziram perdas Se você tiver uma EA multi-moeda, então poderá ser útil também definir o quanto você deseja investir não apenas por posição e no total, mas também como Muito por market-currency. Como: 2 riscos por pedido, 10 por mercado e 20 no total. Esta é uma biblioteca de registro muito simples, útil para criar logs que podem ser gravados no terminal MT4 e salvos no disco em um arquivo. Log externo de log de string log. txt externo bool loggingActive false extern bool logToFile false Define a posição do arquivo de log arquivo de arquivo de arquivo e nome de arquivo do arquivo de log void setLogFile (arquivo de seqüência) logFile arquivo Permite o registro no arquivo em diskspace void enableFileLogging () LogToFile true Desabilita o registro no arquivo em diskspace void disableFileLogging () logToFile false Imprime o log para o diário e salva o log para o arquivo está selecionado void printLog (log de cordas) Apenas imprime ou salve logs, se o loging for ativado se (loggingActive) Se logar no arquivo É selecionado, salve log string no disco se (logToFile) int lidar com FileOpen (logFile. FILEBIN FILEREAD FILEWRITE.) If (lt. Lt 1) Imprimir (LOGGING: Erro ao abrir o arquivo) return (0) FileWriteString (handle. Log. StringLen (log )) FileClose (identificador) Imprima a cadeia log para journal Print (log) Eu acho que essa função deve ser auto-explicativa. Você pode ativar ou desativar a funcionalidade de log e ativar ou desativar o log para arquivar. As mensagens de registro só serão gravadas no Terminal e não no disco. PrintLog (log de string) - Imprime a string no diário quando o registro está ativado e também no arquivo se o login no arquivo estiver ativado. Eu sei que o stderror. mqh vem com o MetraTrader, mas escrevi minha própria versão. Isso porque eu posso incluir meus próprios códigos de erro em mensagens muito simples. Mas, por enquanto, apenas os erros de tempo de execução do Mower e os erros do servidor são implementados. ---- erros devolvidos do servidor comercial definir ERRNOERROR 0 definir ERRNORESULT 1 definir ERRCOMMONERROR 2 definir ERRINVALIDTRADEPARAMETERS 3 definir ERREERVERBUSY 4 definir ERROLDVERSION 5 definir ERRNOCONNECTION 6 definir ERRNOTENOUGHRIGHTS 7 definir ERRTOOFREQUENTREQUESTS 8 definir ERRMALFUNCTIONALTRADE 9 definir ERRACCOUNTDISABLED 64 definir ERRINVALIDACCOUNT 65 definir ERRTRADETIMEOUT 128 definir ERRINVALIDPRICE 129 definem ERRINVALIDSTOPS 130 definem ERRINVALIDTRADEVOLUME 131 definem ERRMARKETCLOSED 132 definem ERRTRADEDISABLED 133 definem ERRNOTENOUGHMONEY 134 definem ERRPRICECHANGED 135 definem ERROFFQUOTES 136 definem ERRBROKERBUSY 137 definem ERRREQUOTE 138 definem ERRORDERLOCKED 139 definem ERRLONGPOSITIONSONLYALLOWED 140 definem ERRTOOMANYREQUESTS 141 definem ERRTRADEMODIFYDENIED 145 definem ERRTRADECONTEXTBUSY 146 definem ERRTRADEEXPIRATIONDENIED 147 definem ERRTRADETOOMANYORDERS 148 - --- mql4 run time errors define ERRNOMQLERROR 4000 define ERRWRONGFUNCTIONPOINTER 4001 define ERRARRAYINDEXOUTOFRANGE 4002 definir ERRNOMEMORYFORCALLSTACK 4003 definir ERRRECURSIVESTACKOVERFLOW 4004 definir ERRNOTENOUGHSTACKFORPARAM 4005 definir ERRNOMEMORYFORPARAMSTRING 4006 definir ERRNOMEMORYFORTEMPSTRING 4007 definir ERRNOTINITIALIZEDSTRING 4008 definir ERRNOTINITIALIZEDARRAYSTRING 4009 definir ERRNOMEMORYFORARRAYSTRING 4010 definir ERRTOOLONGSTRING 4011 definir ERRREMAINDERFROMZERODIVIDE 4012 definir ERRZERODIVIDE 4013 definir ERRUNKNOWNCOMMAND 4014 definir ERRWRONGJUMP 4015 definir ERRNOTINITIALIZEDARRAY 4016 definir ERRDLLCALLSNOTALLOWED 4017 definir ERRCANNOTLOADLIBRARY 4018 definir ERRCANNOTCALLFUNCTION 4019 definir ERREXTERNALCALLSNOTALLOWED 4020 definir ERRNOMEMORYFORRETURNEDSTR 4021 definir ERRSYSTEMBUSY 4022 definir ERRINVALIDFUNCTIONPARAMSCNT 4050 definir ERRINVALIDFUNCTIONPARAMVALUE 4051 definir ERRSTRINGFUNCTIONINTERNAL 4052 definir ERRSOMEARRAYERROR 4053 definir ERRINCORRECTSERIESARRAYUSING 4054 definir ERRCUSTOMINDICATORERROR 4055 definir ERRINCOMPATIBLEARRAYS 4056 definir ERRGLOBALVARIABLESPROCESSING 4057 defi ne ERRGLOBALVARIABLENOTFOUND 4058 definir ERRFUNCNOTALLOWEDINTESTING 4059 definir ERRFUNCTIONNOTCONFIRMED 4060 definir ERRSENDMAILERROR 4061 definir ERRSTRINGPARAMETEREXPECTED 4062 definir ERRINTEGERPARAMETEREXPECTED 4063 definir ERRDOUBLEPARAMETEREXPECTED 4064 definir ERRARRAYASPARAMETEREXPECTED 4065 definir ERRHISTORYWILLUPDATED 4066 definir ERRTRADEERROR 4067 definir ERRENDOFFILE 4099 definir ERRSOMEFILEERROR 4100 definir ERRWRONGFILENAME 4101 definir ERRTOOMANYOPENEDFILES 4102 definir ERRCANNOTOPENFILE 4103 definir ERRINCOMPATIBLEFILEACCESS 4104 definir ERRNOORDERSELECTED 4105 definir ERRUNKNOWNSYMBOL 4106 definir ERRINVALIDPRICEPARAM 4107 definir ERRINVALIDTICKET 4108 definir ERRTRADENOTALLOWED 4109 definir ERRLONGSNOTALLOWED 4110 definir ERRSHORTSNOTALLOWED 4111 definir ERROBJECTALREADYEXISTS 4200 definir ERRUNKNOWNOBJECTPROPERTY 4201 definir ERROBJECTDOESNOTEXIST 4202 definir ERRUNKNOWNOBJECTTYPE 4203 definir ERRNOOBJECTNAME 4204 definir ERROBJECTCOORDINATESERROR 4205 definir ERRNOSPECIFIEDSUBWINDOW 4206 de OK ERRSOMEOBJECTERROR 4207 string ErrorDescription (código int) switch (código) caso ERRNOERROR. Imprimir (sem erro retornado) break case ERRNORESULT. Imprimir (Nenhum erro retornado, mas o resultado é desconhecido) break case ERRCOMMONERROR. Imprimir (erro comum) caso de ruptura ERRINVALIDTRADEPARAMETERS. Imprimir (Parâmetros de comércio inválidos) break case ERRSERVERBUSY. Print (O servidor de comércio está ocupado) break case ERROLDVERSION. Imprimir (versão antiga do terminal do cliente) break case ERRNOCONNECTION. Imprimir (sem conexão com o servidor de comércio) quebra o caso ERRNOTENOUGHRIGHTS. Imprimir (Não há direitos suficientes) break case ERRTOOFREQUENTREQUESTS. Impressão (Solicitações muito frequentes) caso de ruptura ERRMALFUNCTIONALTRADE. Impressão (operação comercial incorreta) caso de falha ERRACCOUNTDISABLED. Print (Conta desativada) break case ERRINVALIDACCOUNT. Imprimir (conta inválida) break case ERRTRADETIMEOUT. Impressão (tempo de espera comercial) caso de ruptura ERRINVALIDPRICE. Imprimir (preço inválido) break case ERRINVALIDSTOPS. Impressão (paradas inválidas) caso de ruptura ERRINVALIDTRADEVOLUME. Caixa de gravação de impressão (volume de comércio inválido) ERRMARKETCLOSED. Impressão (Mercado fechado) caso de falha ERRADIZADO. Imprimir (Comércio is disabled) break case ERRNOTENOUGHMONEY. Imprimir (Não dinheiro suficiente) break case ERRPRICECHANGED. Imprimir (Preço alterado) caso de ruptura ERROFFQUOTES. Imprimir (Off quo)) break case ERRBROKERBUSY. Imprimir (Broker está ocupado) break case ERRREQUOTE. Caixa de gravação Print (Requote) ERRORDERLOCKED. O bloco de gravação Print (Order is locked) ERRLONGPOSITIONSONLYALLOWED. Impressão (posições longas somente permitidas) caso de ruptura ERRTOOMANYREQUESTS. Imprimir (Demasiados pedidos) caso de ruptura ERRADADEMODIFYDENIED. Imprimir (Modificação negada por ordem muito próxima ao mercado) break case ERRTRADECONTEXTBUSY. O contexto Print (Contexto comercial está ocupado) ERRTRADEEXPIRATIONDENIED. Imprimir (Expirações são negadas pelo corretor) break case ERRTRADETOOMANYORDERS. Imprimir (A quantidade de pedidos pendentes e pendentes atingiu o limite definido pelo corretor.) Caso de interrupção ERRNOMQLERROR. Imprimir (sem erro) break case ERRWRONGFUNCTIONPOINTER. Imprimir (ponteiro de função incorreta) caso de ruptura ERRARRAYINDEXOUTOFRANGE. Imprimir (Índice de matriz está fora do intervalo) caso de ruptura ERRNOMEMORYFORCALLSTACK. Imprimir (sem memória para pilha de chamadas de função) caso de ruptura ERRRECURSIVESTACKOVERFLOW. Impressão (estouro de pilha recursiva) quebra case ERRNOTENOUGHSTACKFORPARAM. Imprimir (Não há pilha suficiente para o parâmetro) caso de ruptura ERRNOMEMORYFORPARAMSTRING. Imprimir (sem memória para string de parâmetro) break case ERRNOMEMORYFORTEMPSTRING. Imprimir (sem memória para string temporária) break case ERRNOTINITIEDSTRING. Imprimir (cadeia não inicializada) caso de ruptura ERRNOTINITIALIZEDARRAYSTRING. Imprimir (cadeia não inicializada na matriz) caso de ruptura ERRNOMEMORYFORARRAYSTRING. Imprimir (sem memória para matriz de matriz) caso de ruptura ERRTOOLONGSTRING. Caixa de impressão (muito longa) caso de ruptura ERRREMAINDERFROMZERODIVIDE. Imprimir (Restante de zero divisão) break case ERRZERODIVIDE. Print (Zero dividir) break case ERRUNKNOWNCOMMAND. Imprimir (comando desconhecido) break case ERRWRONGJUMP. Imprimir (salto errado (erro nunca gerado)) break case ERRNOTINITIALIZEDARRAY. Impressão (matriz não inicializada) caso de ruptura ERRDLLCALLSNOTALLOWED. Imprimir (chamadas DLL não são permitidas) caso de ruptura ERRCANNOTLOADLIBRARY. Imprimir (Não é possível carregar a biblioteca) caso de ruptura ERRCANNOTCALLFUNCTION. Imprimir (Não é possível chamar função) caso de falha ERREXTERNALCALLSNOTALLOWED. Imprimir (as chamadas de função especializadas não são permitidas) break case ERRNOMEMORYFORRETURNEDSTR. Imprimir (Memória insuficiente para string temporária retornada da função) break case ERRSYSTEMBUSY. Imprimir (O ​​sistema está ocupado (erro nunca gerado)) caso de falha ERRINVALIDFUNCTIONPARAMSCNT. Imprimir (contagem de parâmetros de função inválidos) caso de falha ERRINVALIDFUNCTIONPARAMVALUE. Imprimir (valor do parâmetro da função inválida) caso de ruptura ERRORTRINGFUNCTIONINTERNAL. Imprimir (erro de função de seqüência de caracteres) caso de ruptura ERREOMEARRAYERROR. Imprimir (Algum erro de array) break case ERRINCORRECTSERIESARRAYUSING. Imprimir (usar matriz de série incorreta) caso de ruptura ERRECINTAINADOR. Imprimir (erro do indicador personalizado) break case ERRINCOMPATIBLEARRAYS. Imprimir (Arrays is incompatible) break case ERRGLOBALVARIABLESPROCESSING. Imprimir (erro de processamento de variáveis ​​globais) break case ERRGLOBALVARIABLENOTFOUND. Imprimir (variável global não encontrada) break case ERRFUNCNOTALLOWEDINTESTING. Imprimir (A função não é permitida no modo de teste) caso de ruptura ERRFUNCTIONNOTCONFIRMED. Imprimir (função não confirmada) caso de ruptura ERRSENDMAILERROR. Imprimir (Enviar erro de email) caso de ruptura ERRORTRINGPARAMETEREXPECTED. Parâmetro print (String parameter expected) ERRINTEGERPARAMETEREXPECTED. Imprimir (parâmetro Inteiro esperado) caso de ruptura ERRDOUBLEPARAMETEREXPECTED. Print (Parámetro duplo esperado) break case ERRARRAYASPARAMETEREXPECTED. Imprimir (Array como parâmetro esperado) break case ERRHISTORYWILLUPDATED. Imprimir (dados do histórico solicitado no estado de atualização) break case ERRTRADEERROR. Imprimir (algum erro na função de negociação) break case ERRENDOFFILE. Imprimir (Fim do arquivo) caso de ruptura ERRSOMEFILEERROR. Erro de impressão (algum erro de arquivo) ERRWRONGFILENAME. Imprimir (nome de arquivo errado) break case ERRTOOMANYOPENEDFILES. Imprimir (Muitos arquivos abertos) quebra o caso ERRCANNOTOPENFILE. Imprimir (Não é possível abrir o arquivo) break case ERRINCOMPATIBLEFILEACCESS. Imprimir (acesso incompatível a um arquivo) break case ERRNOORDERSELECTED. Imprimir (sem ordem selecionada) break case ERRUNKNOWNSYMBOL. Imprimir (símbolo desconhecido) break case ERRINVALIDPRICEPARAM. Imprimir (preço inválido) break case ERRINVALIDTICKET. Caixa de gravação de impressão (cartão inválido) ERRADADADOTORIZADA. Imprimir (O ​​comércio não é permitido - Ative a caixa de seleção - Ajando a negociação ao vivo - nas propriedades experientes) caso de falha ERRLONGNOTALLOWED. Imprimir (Longs não são permitidos - Verifique as propriedades do especialista) break case ERRSHORTSNOTALLOWED. Imprimir (Shorts não são permitidos - Verifique as propriedades experientes) break case ERROBJECTALREADYEXISTS. Imprimir (Objeto já existe) break case ERRUNKNOWNOBJECTPROPERTY. Imprimir (objeto do objeto desconhecido) break case ERROBJECTDOESNOTEXIST. Imprimir (Objeto não existe) caso de falha ERRUNKNOWNOBJECTTYPE. Tipo de gravação de impressão (tipo de objeto desconhecido) ERRNOOBJECTNAME. Imprimir (sem nome do objeto) caso de falha ERROBJECTCOORDINATESERROR. Imprimir (erro de coordenadas do objeto) caso de ruptura ERRNOSPECIFIEDSUBWINDOW. Cópia de impressão (sem sub-janela especificada) ERRSOMEOBJECTERROR. Imprimir (algum erro na função do objeto) quebra ErrorDescription (código int) - retorna a descrição do erro para o código especificado e heres outra EA simples que usa algumas das funções que foram fornecidas nas postagens anteriores. Heres como funciona. Ele usa 3 médias móveis exponenciais - rápido, médio e lento em gráficos diários. E apenas algumas regras simples: Compre quando estamos em tendência de alta Vender quando estamos em tendência de baixa tendência de alta. MA rápido é maior do que MA médio, MA médio é maior do que o MA lento para a atual tendência Bearish da barra semanal. MA rápido é menor do que MA médio, MA médio é menor do que o MA lento para a barra semanal atual. Isso deve impedir que vendamos, quando estamos em um mercado de alta e de comprar enquanto estamos no mercado de baixa. Os sinais de compra e venda também são gerados com as mesmas 3 médias móveis: sinal de compra. MA médio cruza MA lento de baixo para cima e MA rápido está acima de MA médio no gráfico diário Vender sinal. MA médio cruza o MA lento de cima para baixo e MA rápido está abaixo do MA médio no gráfico diário Se estamos em uma tendência de alta, procurando sinais de compra. E se estamos em tendência de baixa, apenas observe sinais de venda. Além disso, essa EA usa paradas para manter os lucros uma vez que foram feitas. E também é possível abrir mais de uma posição ao mesmo tempo (veja definir MAXORDERS). Definir MAXORDERS 5 Indicador Técnico Variáveis ​​extern int FastMA 8 extern int MediumMA 21 extern int SlowMA 55 extern int TrailStop 200 extern int InitialSL 200 Verificar para condições de mercado otimizadas bool isBullishMarket () iMA duplo rápido (Symbol (), PERIODW1. FastMA. 0. MODEEMA PRICECLOSE 0) iMA duplo médio (Symbol (), PERIODW1. MediumMA. 0. MODEEMA. PRICECLOSE. 0) iMA duplo lento (Symbol (), PERIODW1. SlowMA. 0. MODEEMA. PRICECLOSE. 0) Bullish: fast gt medium Gt lento no gráfico semanal se ((fast gt medium) ampamp (médio gt lento)) return (true) else return (false) Verifique se há condições de mercado baixas bool isBearishMarket () iGA duplo rápido (Symbol (), PERIODW1. FastMA. 0 MODEEMA PRICECLOSE 0) iMA duplo médio (Symbol (), PERIODW1. MediumMA. 0. MODEEMA. PRICECLOSE. 0) iMA duplo lento (Symbol (), PERIODW1. SlowMA. 0. MODEEMA. PRICECLOSE. 0) Bullish: rápido Lt lento e lento no gráfico semanal se ((fast lt medium) ampamp (médio lt slo W)) return (true) else return (false) Procure um sinal de compra bool buySignalOccured () double currentFast iMA (Symbol (), PERIODD1. FastMA. 0. MODEEMA. PRICECLOSE. 0) duplo anteriorMedium iMA (Symbol (), PERIODD1. MediumMA. 0. MODEEMA. PRICECLOSE. 1) double currentMedium iMA (Symbol (), PERIODD1. MediumMA. 0. MODEEMA. PRICECLOSE. 0) double previousSlow iMA (Symbol (), PERIODD1. SlowMA. 0. MODEEMA. PRICECLOSE. 1) dual currentSlow iMA (Symbol (), PERIODD1. SlowMA. 0. MODEEMA. PRICECLOSE. 0) se (currentFast gt currentMedium) se ((previousMedium lt previousSlow) ampamp (currentMedium gt currentSlow )) Retorno (verdadeiro) retorno (falso) Procure um sinal de venda bool sellSignalOccured () double currentFast iMA (Symbol (), PERIODD1. FastMA. 0. MODEEMA. PRICECLOSE. 0) double previousMedium iMA (Symbol (), PERIODD1. MediumMA 0. MODEEMA. PRICECLOSE. 1) double currentMedium iMA (Symbol (), PERIODD1. MediumMA. 0. MODEEMA. PRICECLOSE. 0) duplo anteriorSlow iMA (Symbol (), PERIODD1. SlowMA. 0. MODEEMA. PRICECLOSE. 1) Dual currentSlow iMA (Symbol (), PERIODD1. SlowMA. 0. MODEEMA. PRICECLOSE. 0) se (currentFast lt cu RrentMedium) se ((anteriorMedium gt previousSlow) ampamp (currentMedium lt currentSlow)) return (true) return (false) Verifique as condições para vender ou compre uma posição void checkForOpen () double lot Apenas troque no início de uma nova barra se (Volume 91 0 93 gt 1) return Verifique a condição de compra no par selecionado se (isBullishMarket ()) se (buySignalOccured ()) lot lotsOptimized (InitialSL Point) newMarketOrder (Symbol (), BUY. muito. Ask - InitialSL Point. 0) Verifique a condição de venda no par selecionado se (isBearishMarket ()) se (sellSignalOccured ()) lot lotsOptimized (InitialSL Point) newMarketOrder (Symbol (), VENDER. Lot. Bid InitialSL Point. 0) Update arrasar stop void updateTrailingStops () Double stploss Iterate através de cada ordem e escolha aqueles que pertencem à nossa EA para (int j 0 j lt OrdersTotal () j) se (OrderSelect (j. SELECTBYPOS. MODETRADES) false) romper se (OrderMagicNumber () MAGICNUMBER OrderSymbol () Symbol ()) Continue se (OrderType () OPBUY) É pedido já na zona de lucro se (Ask - TrailStop Point gt OrderOpenPrice ()) É nova perda acima das ordens atuais stoploss se (Ask - TrailStop Point gt OrderStopLoss ()) OrderModify (OrderTicket ( ), OrderOpenPrice (), Ask - TrailStop Point. 0. 0. Azul) continue se (OrderType () OPSELL) É ordem já na zona de lucro se (Bid TrailStop Point lt OrderOpenPrice ()) É nova perda abaixo das ordens atuais stoploss se ( Bid TrailStop Point lt Ord ErStopLoss ()) OrderModify (OrderTicket (), OrderOpenPrice (), Bid TrailStop Point. 0. 0. Azul) Continuar Ponto de partida do perito nulo de partida () se (MediumMA lt FastMA) retornar se (SlowMA lt MediumMA) retornar Atualizar nossos gerentes de pedidos e dinheiro updateMoneyManager () updateOrderManager () Atualização de arranque pára - não usamos uma venda Sinal para fechar uma posição, isso poderia ser implementado mais tarde. Mas paragens de arrastar devem dar bons resultados, quer atualizarTrailingStops () Verificar para abrir uma posição se (countOpenOrders () lt MAXORDERS) checkForOpen () Heres a parte que pode ser otimizada: extern int FastMA 8 extern int MediumMA 21 extern int SlowMA 55 extern int TrailStop 200 extern int InitialSL 200 FastMA, MediumMA e SlowMA são os períodos para as médias móveis exponenciais. InitialSL define a perda de parada inicial que será usada quando uma nova posição for aberta. TrailingStop define o tamanho da parada final em pips. Algumas melhorias possíveis Este sistema é para fins de aprendizagem e não deve ser usado em negociação ao vivo - você pode otimizá-lo e testá-lo em uma conta de demonstração, se desejar. É simples e há muitas coisas que devem ser melhoradas antes de usá-lo em uma conta ao vivo, como por exemplo: Melhor detecção da tendência geral do mercado - uma simples melhoria seria não usar os mesmos períodos de média móvel para o gráfico diário e semanal Aberto Mais posições quando o mercado se move na direção desejada. Não espere até que outro sinal de compra ocorra, mas abra uma nova posição se já estivermos em zona de lucro com a primeira ordem e as chances são de que não há mudança de tendência na visão Faça uso de melhor gerenciamento de dinheiro e risco. Backtesting e otimização Eu tomei 2007 como período de backtesting e usei esses valores: Entre todos os resultados obtidos, escolhi um com um bom resultado (gt 26.000 lucro) e um drawdown de Então eu usei esses valores para testá-lo para 2008: gt 40.000 lucro Mas isso foi um sortudo. Outras configurações com diferentes valores executados de ruim para realmente, muito ruim. Então, ainda há muito a fazer: melhorar o gerenciamento de risco e dinheiro melhorar a necessidade de gerenciamento de pedidos para uma melhor detecção de tendências gerais, desenvolver melhores sinais adicionar a posições lucrativas. Permitir abrir mais pedidos e não esperar por outro sinal, mas abrir quando já são feitos grandes lucros reduzidos perdem rapidamente. Não use parada inicial fixa, mas calcule-a (usando o ATR, por exemplo) melhor backtesting e otimização: otimize para 2002 e faça o backtest para 2003. selecione algumas configurações e faça backtest também para 2004. se livre das configurações que apresentaram desempenho fraco e posterior para 2005 com Configurações restantes e assim por diante. Até ter uma boa configuração que tenha funcionado bem durante um período mais longo Se você tiver alguma dúvida ou melhorias, avise-me. Qualquer comentário seja bem-vindo 3ma. mq4 6 KB 321 downloads Que muito trabalho você colocou aqui. Obrigado pelo seu esforço. Eu não tenho suas habilidades de programação. Alguns comentários: isso pode ser minha culpa devido à instalação incorreta. A EA está enviando um tamanho de lote incorreto. Eu estava recebendo 131 erros, então coloquei alguns comandos de impressão no código para ver qual era o tamanho do lote. Os comandos Imprimir estão na linha antes das novas linhas do Marcador. Em seguida, abra o Centro de História em MT4 (pressione F2), selecione o par de moedas na lista de símbolos à esquerda e selecione o prazo mais baixo, 1 minuto (clique duas vezes). Pressione quotDownloadquot e responda quotOKquot quando você receber o aviso. Pode levar alguns minutos até que todo o valor histórico tenha sido baixado. Eu tenho velas de 3,5 minutos de Mio de 1 minuto, ou seja, os últimos 10 anos em minutos devem ser suficientes. Você pode fazer isso com cada período de tempo e moeda, ou usar o script quotperiodconverterquot incluído, que vem com o MT4. Eu não acho que você precisa baixar para cada período de tempo ou usar o timeconverter se os dados do histórico forem baixados através do centro de histórico. Quando eu baixar 1 min para um par de moedas com o centro de histórico, todos os cronogramas de tempo padrão são preenchidos e disponíveis quando terminar. O período de conversor só seria usado para intervalos de tempo personalizados. Se você importar dados que foram baixados externamente (como Alpari), o conversor de período deve ser usado para qualquer período de tempo diferente de 1min. Estou simplesmente surpreso quando leio seu quotMy First EAquot thread. Leia a API ontem e publique o primeiro EA Today. Esta é a capacidade de um programador experiente e, como comerciante, você está indo na direção certa. You have noticed general mistakes soon and are trying to correct them soon. Your quotto doquot list is perfect also. You are so capable enough to do most anything you want, but never forget to be simple. This is a statement that is posted in other forex forum recently and I totally agree. quotI know many who are real PRO traders and they say K. I.S. S Keep it simple system. quot Most trading system that has too many parameters that can quotadjustquot to the market (its what HAPPEND in the past) doesnt work well. Keep your eye on risk management and how to exit the market, then you will be successfull. The reasons why most traders will fail are 1) overtrade (risk too much at a time) 2) predict the future too much (especially by indicators) and underestimate randomness of the market 3) take profit too early and stop loss too late (both are related to the exit) 4) too complicated minded and just cant be consistent Thank you for posting and Good luck. Ive got a small present for you. These are the codes to autodetect and correct a problem of the broker that has quotone more digitquot. For example, most brokers have 4 price digits for EURUSD. (example 1.2345) But Alpari (I dont know whether there are another brokers or not) has 5 digits (example 1.23456) For JPY cross, most brokers gives 123.45 and Alpari gives 123.456. This causes an error when you use pips based integer value (stoploss or takeprofit etc.). Worst of all, if you calculate lot size from pips based stoploss, It returns wrong lot size. It will cause fatal malfunction for risk management. It can be used like this. (Maybe you can do it more sophisticated and universal way) int DQADJ DeciQuoteAdjuster() SL by pips int SLpips StopLossDQADJ SL decision double SL Ask - StopLossDQADJPoint lot size decision double RiskAmount AccountFreeMargin() (RiskRate100) double lot RiskAmount (PipValueStopLossDQADJ) StopLoss is pips based integer. PipValue means PL value for 1lot and 1pip. return(DeciQuoteADJ) return 1 or 10 I wanted to test EA 2 but the file common. mqh is missing. where can I find it One more question. I am new to all this. I use IMA function in the code as below. It seems to me that the IMA call does not return current values I want it to buy or sell when after the gold cross but it seems to do it elsewhere. Am I missing something. Maybe someone wants to cooperate on the project Order details extern int Slippage 3 How much slip can we accept extern double Lots 0.01 extern int MagicNumber 0 Stops extern bool UseStopLoss False No stops for the Axitrader extern int StopLoss 30 extern bool UseTakeProfit False extern int TakeProfit 60 extern bool UseTrailingStop True extern int TrailingStop 30 extern bool EachTickMode True extern bool OrderNoLossProfit True for axitrader ------------------------------------------------------------------ expert initialization function ------------------------------------------------------------------ int init() ---- Ticks back int BuyBackTicks 2 back ticks to check if time low lt high to buy int CloseBuyBackTicks 0 int SellBackTicks 2 back ticks to check if time low lt high to buy int CloseSellBackTicks 0 MA int MALow 5 int MAHigh 8 int Current 0 Current Bar int Order 0 int Ticket 0 int BarCount double StopLossLevel, TakeProfitLevel double BuyBackLo w iMA(NULL, 0, MALow, 0, MODEEMA, PRICECLOSE, Current BuyBackTicks) double BuyBackHigh iMA(NULL, 0, MAHigh, 0, MODEEMA, PRICECLOSE, Current BuyBackTicks) double BuyNowLow iMA(NULL, 0, MALow, 0, MODEEMA, PRICECLOSE, Current 0) double BuyNowHigh iMA(NULL, 0, MAHigh, 0, MODEEMA, PRICECLOSE, Current 0) double SellBackLow iMA(NULL, 0, MALow, 0, MODEEMA, PRICECLOSE, Current SellBackTicks) double SellBackHigh iMA(NULL, 0, MAHigh, 0, MODEEMA, PRICECLOSE, Current SellBackTicks) double SellNowLow iMA(NULL, 0, MALow, 0, MODEEMA, PRICECLOSE, Current 0) double SellNowHigh iMA(NULL, 0, MAHigh, 0, MODEEMA, PRICECLOSE, Current 0) double CloseBuyBackLow iMA(NULL, 0, MALow, 0, MODEEMA, PRICECLOSE, Current CloseBuyBackTicks) double CloseBuyBackHigh iMA(NULL, 0, MAHigh, 0, MODEEMA, PRICECLOSE, Current CloseBuyBackTicks) double CloseBuyNowLow iMA(NULL, 0, MALow, 0, MODEEMA, PRICECLOSE, Current 0) double CloseBuyNowHigh iMA(NULL, 0, MAHigh, 0, MODEEMA, PRICECLOSE, Current 0) double C loseSellBackLow iMA(NULL, 0, MALow, 0, MODEEMA, PRICECLOSE, Current CloseSellBackTicks) double CloseSellBackHigh iMA(NULL, 0, MAHigh, 0, MODEEMA, PRICECLOSE, Current CloseSellBackTicks) double CloseSellNowLow iMA(NULL, 0, MALow, 0, MODEEMA, PRICECLOSE, Current 0) double CloseSellNowHigh iMA(NULL, 0, MAHigh, 0, MODEEMA, PRICECLOSE, Current 0) Alert(quotBuyBackLow, BuyBackHighquot, BuyBackLow, quot quot, BuyBackHigh) Alert(quotSellBackLow, SellBackHighquot, SellBackLow, quot quot, SellBackHigh) Check position bool IsTrade False for (int i 0 i lt OrdersTotal() i ) OrderSelect(i, SELECTBYPOS, MODETRADES) Select order by position in the trading pool bool OrderSelect( int index, int select, int poolMODETRADES) The function selects an order for further processing. It returns TRUE if the function succeeds. It returns FALSE if the function fails. To get the error information, one has to call the GetLastError() function. The pool parameter is ignored if the order is selected by the ticket number. The ticket number is a unique order identifier. To find out from what list the order has been selected, its close time must be analyzed. If the order close time equals to 0, the order is open or pending and taken from the terminal open positions list. One can distinguish an open position from a pending order by the order type. If the order close time does not equal to 0, the order is a closed order or a deleted pending order and was selected from the terminal history. They also differ from each other by their order types. Parameters: index - Order index or order ticket depending on the second parameter. select - Selecting flags. It can be any of the following values: SELECTBYPOS - index in the order pool, SELECTBYTICKET - index is order ticket. pool - Optional order pool index. Used when the selected parameter is SELECTBYPOS. It can be any of the following values: MODETRADES (default)- order selected from trading pool(opened and pending orders), MODEHISTORY - order selected from history pool (closed and canceled order). Closing existing orders if (OrderType() OPSELL ampamp OrderSymbol() Symbol()) Sell order found for currency pair same as chart close existing order if condition fulfilled(to be specified below) Closing Strategy here if (CloseSellBackLow lt CloseSellBackHigh ampamp CloseSellNowLow gt CloseSellNowHigh) Order SIGNALCLOSESELL if (CloseSellBackLow lt CloseSellBackHigh ampamp CloseSellNowLow gt CloseSellNowHigh)Order SIGNALCLOSEBUY if (Order SIGNALCLOSEBUY) OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, DarkOrange) continue Trailing stop if(UseTrailingStop ampamp TrailingStop gt 0) if(Bid - OrderOpenPrice() gt Point TrailingStop) if(OrderStopLoss() lt Bid - Point TrailingStop) OrderModify(OrderTicket(), OrderOpenPrice(), Bid - Point TrailingStop, OrderTakeProfit(), 0, MediumSeaGreen) if (EachTickMode) BarCount Bars continue if (OrderType() OPBUY ampamp OrderSymbol() Symbol()) close existing order if condition fulfilled (to be specified below) Closing Strategy her e if (CloseSellBackLow lt CloseSellBackHigh ampamp CloseSellNowLow gt CloseSellNowHigh) Order SIGNALCLOSESELL if (Order SIGNALCLOSESELL) OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, MediumSeaGreen) if (Order SIGNALBUY) if (AccountFreeMargin() lt (1000 Lots)) Alert(quotWe have no money. Free Margin quot, AccountFreeMargin()) return(0) StopLossLevel FuncStopLossLevel(UseStopLoss, StopLoss) TakeProfitLevel FuncTakeProfitLevel(UseTakeProfit, TakeProfit) Ticket OrderSend(Symbol(), OPBUY, Lots, Ask, Slippage, StopLossLevel, TakeProfitLevel, quotBuy(quot MagicNumber quot)quot, MagicNumber, 0, DodgerBlue) Alert(quotBuying ticket quot, Ticket, quotError code quot, GetLastError() ) if(Ticket gt 0) if (OrderSelect(Ticket, SELECTBYTICKET, MODETRADES)) Alert(quotBUY order opened. quot, OrderOpenPrice()) if (OrderNoLossProfit) if (StopLoss gt 0 TakeProfit gt0) xxx OrderModify(OrderTicket(), OrderOpenPrice(), Ask Point StopLoss, Ask TakeProfit Point, 0, DarkOrange) else Alert(quotError opening BUY order. quot, GetLastError()) SELL SELL SELL Found gold cross: Insert Selling Strategy if (SellBackLow gt SellBackHigh ampamp SellNowLow lt SellNowHigh) Order SIGNALSELL if (Order SIGNALSELL) Check free margin if (AccountFreeMargin() lt (1000 Lots)) Alert(quotWe have no money. Free Margin quot, AccountFreeMargin()) return(0) if (UseStopLoss) StopLossLevel Bid StopLoss Point else StopLossLevel 0.0 if (UseTakeProfit) TakeProfitLevel Bid - TakeProfit Point else TakeProfitLevel 0.0 Ticket OrderSend(Symbol(), OPSELL, Lots, Bid, Slippage, StopLossLevel, TakeProfitLevel, quotSell(quot MagicNumber quot)quot, MagicNumber, 0, DeepPink) if(Ticket gt 0) if (OrderSelect(Ticket, SELECTBYTICKET, MODETRADES)) Alert(quotSELL order opened. quot, OrderOpenPrice()) modify order with stoploss, take profit for axitrader xxx if (OrderNoLossProfit) if (StopLoss gt 0 TakeProfit gt0) OrderModify(OrderTicket(), OrderOpenPrice(), Ask Point StopLoss, Ask TakeProfit Point, 0, DarkOrange) else Alert(quotError opening SELL order. quot, GetLastError()) Alert(quotSelling Ticket quot, Ticket, quotError code quot, GetLastError()) double FuncStopLossLevel(bool UseStopLoss, double StopLoss) double StopLossLevel if (UseStopLoss) StopLossLevel Ask - StopLoss Point else StopL ossLevel 0.0 return (StopLossLevel) double FuncTakeProfitLevel(bool UseTakeProfit, double TakeProfit) double TakeProfitLevel if (UseTakeProfit) TakeProfitLevel Ask - TakeProfit Point else TakeProfitLevel 0.0Opening a Trade Using OrderSend In the last module, we went over the basic Expert Advisor and how to create input parameters. If you8217d like to review that module, click here: The Expert Advisor. Today we are going to do something more useful with an Expert Advisor: open a trade. The MetaTrader function used to open a trade is called 8220OrderSend8221. This table details each of the parameters required to set when using the function. The symbol of the currency. The type of order to open. See the table below. The number of lots to open. The preferred open price. The number of points the preferred open price may slip. The stoploss set in the order on the brokers server. This value must be calculated using the price and the currency point value. The takeprofit set in the order on the brokers server. This value must be calculated using the price and the currency point value. A text comment that can be seen from within the MetaTrader platform when viewing open orders. The color of the arrow that will appear on the price chart when the OrderSend function is successful. Most of these parameters are pretty straight forward, but a few require a bit of an explanation. The 8220 symbol 8221 parameter is the name of the currency pair. You can use the MT function 8220Symbol()8221 which will automatically use the currency of the chart that the EA is running on. Or you can even define any name in quotes, for example 8220EURUSD8221. (Note: Opening a currency different than the one that the EA is running requires some special techniques which I8217ll cover in a later module.) The 8220 cmd 8221 parameter is the command that tells the broker8217s server what you want to do. The choices for a market order are OPBUY or OPSELL 8211 open a Buy or Sell trade. The 8220 volume 8221 parameter is the number of lots you8217d like to open or close. The 8220 price 8221 parameter is the preferred price. On MT, I8217ve found this value should be set to the 8220Ask8221 price for opening Buy orders and the 8220Bid8221 price for opening Sell orders. Any other values seem to cause the function to fail. The 8220 slippage 8221 parameter is how many points you8217ll allow the trade to slip and still complete the order. For example, suppose you8217d like to buy the EURUSD at 1.3595 and the slippage is set to 3 8211 you might pay as much as 1.359531.3598. (This may look bad, but if you set your slippage too small you may not get the trade at all.) The 8220 stoploss 8221 parameter is the limit for how far the trade can go against you before the broker8217s server closes the position. (Note: Your EA does not need to be running for the stoploss to work. This is a value stored on the broker8217s system.) This value will be lower than your open price for Buy orders and greater than the open price for Sell orders. Both the stoploss and takeprofit parameters must be in exact terms of the price, so you need to do some math here. For example, if you8217d like a stoploss of 15 points, you need to subtract 15 from the open price (for an open price of 1.3595): stoploss 1.3595 8211 0.0015 1.3580 Fortunately, there is an easy way to get the 0.0015 number using the 8220Point8221 function: 15 Point 0.0015 This way, you can work with a number like 15 instead of 0.0015. (I personally think the OrderSend function could have been written to simply accept a relative value like 15 for the stoploss instead of requiring an absolute price value like 1.3580). The 8220 takeprofit 8221 parameter is the limit of how far a trade can go in your direction before it closes for a profit. This value will be higher than your open price for Buy orders and less than the open price for Sell orders. The rest of this parameter is just like the stoploss. The 8220 comment 8221 parameter can be any text. It is saved with the trade and appears in the comment window in the trading terminal. I usually put the name of the EA in this field so when I look at my open trades I can see what EA has opened each. The 8220 magic 8221 parameter is a number that you can assign to the trade so that you can identify it later. We8217ll see exactly how in a later module on the OrderSelect function. The 8220 expiration 8221 parameter holds an expiration time for pending orders. It has no meaning for market orders. (In my experience it does not work for pending orders either.) The 8220 arrowcolor 8221 parameter allows you to choose the color of the arrow that is drawn on the chart when the trade is opened. Now that we have described all of the input parameters, I8217ll make a quick note about the 8220return value8221. The OrderSend function will return a value back after it has finished running. In MQL, like most languages, a negative number is a bad thing and zero or a positive number is usually a good thing 8211 indicating the function executed successfully. We8217ll capture and check the value return from the OrderSend function so we8217ll know if it worked and actually opened a trade successfully. Note: All of the information about the OrderSend function is available from within the MetaEditor. The help file is very useful. Even as an experienced MQL programmer, I refer to the help often. (From within the MetaEditor, select View-gtNavigator and then use the search option to find your information.) So, let8217s see what the MQL code looks like. Here is the MQL code for the OrderSend function. extern int stoploss200 the takeprofit extern int takeprofit200 the number of lots extern double lots 1.0 this function will be called each time new price data arrives from the broker int start() int status OrderSend( Symbol(), the synbol for this chart OPBUY, a buy order lots, number of lots Ask, use the ask price for a BUY 3, allow the price up to move 3 points Ask 8211 (stoplossPoint), stop Bid (takeprofitPoint), limit 8220My Simple EA8221, comment to see in TerminalCompany 8675309, a unique to id this trade 0, expiration, doesn8217t work Blue a blue arrow ) if( status lt 0 ) Comment(8220OrderSend Failed. Error8221, GetLastError()) return(0) Here are some common error codes returned from the OrderSend function that you may come across as you develop your EA8217s: ERRINVALIDPRICE 8211 usually the wrong preferred price: For Buy, use Ask, for. use Bid. ERRINVALIDSTOPS 8211 usually bad math with the stoploss or takeprofit values, or they are zero and the broker will not accept zero. ERRINVALIDTRADEVOLUME 8211 the lot value is invalid, usually a problem with mini or micro lots. If you have trouble, try setting this to 1.0 to see if the error goes away. ERRNOTENOUGHMONEY 8211 self explanatory, if you are testing using a demo account this can happen often 8211 just open another demo account. This wraps up our lesson on opening a trade with an Expert Advisor. (To open a Sell trade, change the 8220cmd8221 parameter to OPSELL and reverse the math on the stoploss and takeprofit.) This limited amount of information is dangerous, so be careful with this code and please, only run this on a demo account Next module we8217ll learn how to use technical indicatorsMQL4 Reference MetaQuotes Language 4 (MQL4) is a built-in language for programming trading strategies. This language is developed by MetaQuotes Software Corp. based on their long experience in the creation of online trading platforms. Using this language, you can create your own Expert Advisors that make trading management automated and are perfectly suitable for implementing your own trading strategies. Besides, using MQL4 you can create your own technical indicators (custom indicators), scripts and libraries. MQL4 contains a large number of functions necessary for analyzing current and previously received quotes, and has built-in basic indicators and functions for managing trade orders and controlling them. The MetaEditor (text editor) that highlights different constructions of MQL4 language is used for writing the program code. It helps users to orientate themselves in the expert system text quite easily. The brief guide contains functions, operations, reserved words, and other language constructions divided into categories, and allows finding the description of every used element of the language. Programs written in MetaQuotes Language 4 have different features and purposes: Expert Advisor is a mechanical trading system linked up to a certain chart. An Expert Advisor starts to run when an event happens that can be handled by it: events of initialization and deinitialization, event of a new tick receipt, a timer event, depth of market changing event, chart event and custom events. An Expert Advisor can both inform you about a possibility to trade and automatically trade on an account sending orders directly to a trade server. Expert Advisors are stored in terminaldirectoryMQL4Experts. Custom Indicator is a technical indicator written independently in addition to those already integrated into the client terminal. Like built-in indicators, they cannot trade automatically and are intended for implementing of analytical functions only. Custom indicators are stored in terminaldirectory MQL4Indicators Script is a program intended for a single execution of some actions. Unlike Expert Advisors, scripts do not process any actions, except for the start event (this requires the OnStart handler function in a script). Scripts are stored in terminaldirectoryMQL4Scripts Library is a set of custom functions intended for storing and distributing frequently used blocks of custom programs. Libraries cannot start executing by themselves. Libraries are stored in terminaldirectoryMQL4Libraries Include File is a source text of the most frequently used blocks of custom programs. Such files can be included into the source texts of Expert Advisors, scripts, custom indicators, and libraries at the compiling stage. The use of included files is more preferable than the use of libraries because of additional burden occurring at calling library functions. Include files can be stored in the same directory as a source file - in this case the include directive with double quotes is used. Another place to store include files is terminaldirectoryMQL4Include, in this case the include directive is used with angle brackets.

Comments

Popular posts from this blog

Streaming Forex Rates Api

Pnb Forex Branch In Delhi

Opções Estratégias Para Ganhos