Monday 28 August 2017

Forex Estratégia 80 20


Estratégia de Forex Estratégia de Forex, Estratégia de Forex Estratégia de Forex Estratégia de Forex Estratégia de Forex Schaff tendência é dificilmente algo revolucionário e novo, mas é bastante rentável e fácil por um tempo considerável, e é baseado no mesmo ciclo de tendência de exibição schaff É complementado por um indicador estocástico. Para o comércio eu recomendo escolher um dos corretores: FxPro ou Alpari (acrescenta 101 depósito) hellip Estratégia Forex 171Moho187 é baseado em um conjunto de indicadores padrão: MACD indicador define a tendência subjacente (sentido de comércio), Momentum 8212 mostra o humor atual Do mercado, eo indicador Fractals fornece um ponto de entrada, então a estratégia fornece um bom lucro dentro de uma tendência, no entanto, isso não significa que é o hellip Hoje publicamos uma estratégia bastante simples, mas eficaz forex 171The double zero187, in Que apenas um indicador eo nível de preço redondo com o fim em dois zeros (para o corretor de quatro dígitos). Para o comércio eu recomendo escolher um dos corretores: FxPro ou Alpari (acrescenta 50 depósito) Apesar da simplicidade desta estratégia, hellip Strategy forex 171Fox187 é riscos bastante excessiva e este fato deve ser considerado quando você transformá-lo em seu conjunto de negociação ) 8212 a relação de perda de stop de lucro em transações às vezes não está no favor do trader8217s, mas a alta precisão dos sinais na entrada para o mercado e filtros adicionais hellip Forex estratégia 171mbush187 à primeira vista pode parecer um pouco confuso e complicado, E realmente para backtesting a estratégia vai exigir muita paciência e rigor, mas na negociação real todo o processo é bastante simples e lógico: o sinal principal é esperado no intervalo H4, onde determinamos a direção do comércio. Next hellip Download MT4 indicator - Money Management Calculadora: MetaTrader 5 - Trading Systems Estratégia de negociação 80-20 Introdução 80-20 é um nome de uma das estratégias de negociação (TS) descritas no livro Street Smarts: Alta Probabilidade Short-Term Trading Strategies Por Linda Raschke e Laurence Connors. Semelhante às estratégias discutidas em meu artigo anterior. Os autores atribuem-na ao estágio quando o preço testa as margens da escala. É também focado em lucrar com falhas falsas e roll-backs das fronteiras. Mas desta vez, analisamos o movimento de preços em um intervalo de histórico significativamente mais curto envolvendo apenas o dia anterior. O tempo de vida de um sinal obtido é também relativamente curto, uma vez que o sistema se destina a negociação intraday. O primeiro objetivo do artigo é descrever o desenvolvimento do módulo de sinal de estratégia comercial 80-20 usando a linguagem MQL5. Então, vamos conectar este módulo à versão ligeiramente editada do robô comercial básico desenvolvido no artigo anterior da série. Além disso, vamos usar o mesmo módulo para o desenvolvimento de um indicador para negociação manual. Como já foi dito, o código fornecido na série de artigos destina-se principalmente a programadores novatos ligeiramente avançados. Portanto, além de seu objetivo principal, o código é projetado para ajudar a passar da programação processual para a orientada a objetos. O código não apresenta classes. Em vez disso, ele implementará completamente estruturas que são mais fáceis de dominar. Outro objetivo do artigo é desenvolver ferramentas que nos permitam verificar se a estratégia ainda é viável hoje, uma vez que Raschke e Connors usaram o comportamento do mercado no final do século passado ao criá-lo. Alguns testes EA com base nos dados de histórico atualizados são apresentados no final do artigo. 80-20 sistema de negociação Os autores nomeiam George Taylors The Taylor Trading Technique. Bem como Steve Moores trabalha na análise de computadores de futuros mercados e Derek Gipsons experiência comercial como base teórica para o seu próprio trabalho. A essência da estratégia de negociação pode ser brevemente descrita da seguinte forma: se os dias anteriores Open e Close preços estão localizados nas áreas de diário diário oposto, então a probabilidade de uma reversão para os dias anteriores abertura é muito alta hoje. Os preços Open e Close dos dias anteriores devem ser localizados próximo às margens da faixa. A reversão deve começar o dia atual (não antes dos dias anteriores a vela é fechada). As regras de estratégia para a compra são as seguintes: 1. Certifique-se de que o mercado abriu na parte superior 20 e fechou na parte inferior 20 da escala diária ontem 2. Aguarde até hoje Baixas quebras nos dias anteriores um pelo menos por 5 carrapatos 3. Coloque uma ordem de compra pendente na margem inferior do intervalo de ontem 4. Uma vez que a ordem pendente desencadeia, defina seu StopLoss inicial nos dias Baixa 5. Use trailing stop para proteger o lucro obtido As regras de entrada de venda são semelhantes, mas a barra de yesterdays deve Ser otimista, uma ordem de compra deve ser localizada na borda superior da barra, enquanto StopLoss deve ser colocado no Alto de hoje. Ainda outro detalhe importante é o tamanho de uma barra diária fechada. De acordo com Linda Raschke, deve ser bastante grande - mais do que o tamanho médio das barras diárias. No entanto, ela não especifica quantos dias de história devem ser levados em consideração ao calcular a faixa diária média. Devemos também ter em mente que o TS é projetado exclusivamente para os exemplos de negociação intraday mostrado no livro usar gráficos M15. O bloco de sinal e o indicador que faz um layout de acordo com a estratégia são descritos abaixo. Você também pode ver alguns screenshots com os resultados da operação do indicador. Eles ilustram claramente padrões correspondentes às regras do sistema e níveis de negociação ligados aos padrões. A análise do padrão deve resultar na colocação de uma ordem de compra pendente. Níveis de negociação apropriados são melhor vistos no cronograma M1: Um padrão semelhante com a direção de negociação oposta no cronograma M5: Seus níveis de negociação (M1 cronograma): Módulo de sinal Permite adicionar o cálculo do nível Take Profit para ilustrar a adição de novas opções para um TS personalizado. Não existe tal nível na versão original, pois apenas uma parada de arrasto é usada para fechar uma posição. Vamos fazer Take Profit dependente do nível mínimo personalizado breakout (TS8020ExtremumBreak), vamos multiplicá-lo pelo TS8020TakeProfitRatio proporção personalizada. Precisaremos dos seguintes elementos da função principal dos módulos de sinal de feGetEntrySignal: status atual do sinal, níveis de entrada e saída calculados (Stop Loss e Take Profit), bem como bordas da gama yesterdays. Todos os níveis são recebidos através de links para as variáveis ​​passadas para a função, enquanto o status de retorno de sinais usa a lista de opções do artigo anterior: enum ENUMENTRYSIGNAL ENTRYBUY, sinal de compra ENTRYSELL, sinal de venda ENTRYNONE, nenhum sinal ENTRYUNKNOWN status não definido ENUMENTRYSIGNAL feGetEntrySignal D1 análise de padrão de duas velas datetime tTime, tempo atual amp duplo dEntryLevel, nível de entrada (link para a variável) amp duplo dSL, nível StopLoss (link para a variável) amplificador duplo dTP, TakeProfit nível (link para a variável) amp duplo dRangeHigh , Alto dos padrões 1 st bar (link para a variável) double amp dRangeLow Baixo dos padrões 1 st bar (link para a variável)) Para detectar um sinal, precisamos analisar as duas últimas barras de tempo D1. Vamos começar a partir do primeiro se ele não atende aos critérios TS, não há necessidade de verificar a segunda barra. Existem dois critérios: 1. O tamanho da barra (diferença entre Alto e Baixo) deve exceder o valor médio para os últimos XX dias (definido pela configuração personalizada TS8020D1ApertoPeríodo) 2. Os níveis de Barra Aberta e Fechada devem estar localizados no lado oposto de 20 O intervalo de barras Se estas condições forem satisfeitas, os preços Alto e Baixo devem ser guardados para utilização posterior. Uma vez que os primeiros parâmetros de barra não mudam dentro de todo o dia, não há nenhum ponto em verificá-los em cada chamada de função. Vamos armazená-los em variáveis ​​estáticas: entrada de configurações personalizadas uint TS8020D1AveragePeriod 20 80-20: Número de dias para calcular a entrada diária média de intervalo uint TS8020ExtremumBreak 50 80-20: Fuga mínima do hierómetro extremum (em pontos) estática ENUMENTRYSIGNAL sePossibleSignal ENTRYUNKNOWN padrões primeiro Barra de direção do sinal variáveis ​​duplas estáticas para armazenar níveis calculados entre carrapatos sdEntryLevel 0, sdSL 0. sdTP 0, sdRangeHigh 0. sdRangeLow 0 verifique a primeira barra de padrões em D1: se (sePossibleSignal ENTRYUNKNOWN) stLastD1Bar tCurrD1Bar 1 st bar não muda esta média diária Diária dupla dAverageBarRange fdAverageBarRange (TS8020D1AveragePeriod, PERIODD1. TTime) if (maRates 0.high maRates 0.low lt dAverageBarRange) 1 st bar não é suficientemente grande sePossibleSignal ENTRYNONE significa nenhum sinal today return (sePossibleSignal) double d20Percents 0.2 (maRates 0.high MaRates 0.low) 20 da escala dos yesterdays se ((barra bearish: maRates 0.open gt maRates 0.high d20Percent barra aberta no superior 20 ampamp ma Tarifas 0.close lt maRates 0.low d20Percents e fechado no inferior 20) (otimista: maRates 0.close gt maRates 0.high d20Percents barra fechada na parte superior 20 ampamp maRates 0.open lt maRates 0.low d20Percents e aberto no inferior 20)) 1 st bar corresponde às condições definem hoje negociação direção para os padrões 1 st bar: sePossibleSignal maRates 0.open gt maRates 0. ENTRYBUY. ENTRYSELL nível de entrada no mercado: sdEntryLevel dEntryLevel sePossibleSignal ENTRYBUY. MaRates 0.low. MaRates 0.high patterns 1 st bar range limites: sdRangeHigh dRangeHigh maRates 0.high sdRangeLow dRangeLow maRates 0.low else 1 st bar openclose os níveis não correspondem às condições sePossibleSignal ENTRYNONE significa nenhum sinal today return (sePossibleSignal) Listagem da função para definir o Intervalo de barras médio dentro do número especificado de barras no período de tempo especificado começando a partir da função de tempo especificada: double fdAverageBarRange (Calcule o tamanho médio da barra int iBarsLimit, quantas barras a considerar ENUMTIMEFRAMES eTF PERIODCURRENT. es timeframe datetime tTime WRONGVALUE quando iniciar o cálculo) double DAverageRange 0 variável para valores de soma se (iBarsLimit lt 1) return (dAverageRange) MqlRates maRates barra info array obtém informações de barra do intervalo de histórico especificado: if (tTime WRONGVALUE) tTime TimeCurrent () int iPriceBars CopyTaxes (Symbol. eTF, tTime, iBarsLimit , MaRates) if (iPriceBars WRONGVALUE) se (LogLevel gt LOGLAVELNONE) PrintFor Mat (s: CopyRates: erro u. FUNÇÃO. (S): Copia: barras de u copiadas de u. FUNCTION. IPriceBars, iBarsLimit) soma de intervalos: int iBar iPriceBars enquanto (iBar-- gt 0 ) DAverageRange maRatesiBar. high valor médio maRatesiBar. low: return (dAverageRange double (iPriceBars)) Existe apenas um critério para os padrões segundo (corrente) breakout da barra da borda do intervalo yesterdays não deve ser menor do que o especificado nas configurações TS8020ExtremumBreak). Assim que o nível é atingido, um sinal para colocar uma ordem pendente aparece: verifique os padrões 2ª barra (atual) em D1: se (sePossibleSignal ENTRYBUY) sdSL dSL maRates 1.low StopLoss para o atual High if (TS8020TakeProfitRatio gt 0 ) SdTP dTP dEntryLevel Ponto TS8020ExtremumBreak TS8020TakeProfitRatio Retorno TakeProfit (é o breakout para baixo claramente visto maRates 1.close lt maRates 0.low Point TS8020ExtremumBreak ENTRYBUY. ENTRYNONE) se (sePossibleSignal ENTRYSELL) sdSL dSL maRates 1.high StopLoss para o hoje Baixo if (TS8020TakeProfitRatio Gt 0) sdTP dTP dEntryLevel Ponto TS8020ExtremumBreak TS8020TakeProfitRatio Retorno TakeProfit (é a divisão ascendente claramente visto maRates 1.close gt maRates 0.high Ponto TS8020ExtremumBreak ENTRYSELL. ENTRYNONE) Salve as duas funções mencionadas acima (feGetEntrySignal e fdAverageBarRange) e as configurações personalizadas relacionadas a Recebendo um sinal para o arquivo de biblioteca mqh. A lista completa está anexada abaixo. Permite nomear o arquivo Signal80-20.mqh e colocá-lo no diretório apropriado da pasta de dados do terminal (MQL5IncludeExpertSignal). Indicador para negociação manual Assim como o EA, o indicador é usar o módulo de sinal descrito acima. O indicador deve informar um comerciante ao receber um sinal de colocação de pedido pendente e fornecer os níveis calculados ordem colocação, Take Profit e Stop Loss níveis. Um usuário pode selecionar um método de notificação uma janela pop-up padrão, alerta por e-mail ou notificação push. É possível escolher tudo de uma vez ou qualquer combinação que você gosta. Outro objetivo indicador é um layout de histórico de negociação de acordo com 80-20 TS. O indicador deve destacar as barras diárias correspondentes aos critérios do sistema e calcular os níveis de negociação calculados. As linhas de nível exibem como a situação evoluiu ao longo do tempo. Para mais clareza, vamos fazer o seguinte: quando o preço toca a linha de sinal, este último é substituído por uma linha de ordem pendente. Quando a ordem pendente é ativada, sua linha é substituída por Take Profit e Stop Loss lines. Estas linhas são interrompidas quando o preço toca um deles (a ordem é fechada). Esse layout facilita a avaliação da eficiência das regras do sistema de negociação e define o que pode ser melhorado. Vamos começar com declarar os buffers e seus parâmetros de exibição. Primeiro, precisamos declarar os dois buffers com o preenchimento da área vertical (DRAWFILLING). O primeiro é destacar o intervalo de barras diário completo do dia anterior, enquanto outro é realçar a área interna apenas para separá-lo do superior e inferior 20 do intervalo usado em TS. Depois disso, declare os dois buffers para a linha de sinal multicolorido ea linha de ordem pendente (DRAWCOLORLINE). Sua cor depende do sentido de negociação. Há outras duas linhas (Take Proft e Stop Loss) com a sua cor restante o mesmo (DRAWLINE) que são para usar as mesmas cores padrão atribuído a eles no terminal. Todos os tipos de exibição selecionados, exceto para uma linha simples, requerem dois buffers cada, portanto o código tem a seguinte aparência: property indicatorchartwindow property indicatorbuffers 10 propriedade indicatorplots 6 property indicatorlabel1 1 st bar do padrão property indicatortype1 DRAWFILLING property indicatorcolor1 clrDeepPink. Propriedade clrDodgerBlue indicatorwidth1 1 property indicatorlabel2 1 st barra da propriedade de padrão indicatortype2 DRAWFILLING property indicatorcolor2 clrDeepPink. Propriedade clrDodgerBlue indicatorwidth2 1 propriedade indicatorlabel3 Propriedade do nível do sinal indicatortype3 DRAWCOLORLINE propriedade indicatorstyle3 STYLESOLID propriedade indicatorcolor3 clrDeepPink. Propriedade clrDodgerBlue indicatorwidth3 2 property indicatorlabel4 Propriedade entry level indicatortype4 DRAWCOLORLINE propriedade indicatorstyle4 STYLEDASHDOT propriedade indicatorcolor4 clrDeepPink. Propriedade clrDodgerBlue indicatorwidth4 2 propriedade indicatorlabel5 Stop Loss propriedade indicatortype5 DRAWLINE propriedade indicatorstyle5 STYLEDASHDOTDOT propriedade indicatorcolor5 clrCrimson propriedade indicatorwidth5 1 property indicatorlabel6 Take Profit propriedade indicatortype6 DRAWLINE propriedade indicatorstyle6 STYLEDASHDOTDOT propriedade indicatorcolor6 clrLime property indicatorwidth6 1 Permite fornecer aos comerciantes a capacidade de desativar o preenchimento dos padrões diários Primeira barra, selecione opções de notificação de sinal e limite a profundidade do layout do histórico. Todas as configurações do sistema de negociação do módulo de sinal também estão incluídas aqui. Para fazer isso, precisamos enumerar preliminarmente as variáveis ​​usadas no módulo, mesmo que algumas delas sejam usadas apenas na EA e não sejam necessárias no indicador: include ltExpertSignalSignal80- 20.mqhgt 80-20 Entrada do módulo de sinal TS Bool ShowOuter true 1 st barra do padrão: Mostra a entrada de gama completa bool ShowInner true 1 st barra do padrão: Mostra a entrada de área interna bool AlertPopup true Alerta: Mostra uma entrada de janela pop-up bool AlertEmail false Alerta: Enviar um eMail Input string AlertEmailSubj Alerta: entrada de assunto do eMail bool AlertPush true Alert: Envia uma entrada de notificação de envio uint BarsLimit 2000 Profundidade do layout do histórico (nas barras TF atuais) ENUMLOGLEVEL LogLevel LOGLEVELNONE Modo de log duplo buff1stBarOuter, buff1stBarOuterZero, buffers para plotar todo o intervalo dos padrões 1 st bar buff1stBarInner, buff1stBarInnerZero, buffers para plotar o interno 60 dos padrões 1 st bar buffSignal, buffSignalColor, linha de sinal buffers buffEntry, BuffEntryColor, buffer de linha pendente buffSL, buffTP, StopLoss e TakeProfit buffers de linhas gdExtremumBreak 0 TS8020ExtremumBreak em preços de símbolo int giD1AveragePeriod 1. valor correto para TS8020D1AveragePeriod giMinBars WRONGVALUE número mínimo necessário de barras para re-cálculo int OnInit () verifica o parâmetro TS8020D1AveragePeriod inserido: GiD1AveragePeriod int (fmin (1. TS8020D1AveragePeriod)) converter pontos para os preços de símbolos: gdExtremumBreak TS8020ExtremumBreak Ponto mínimo necessário número de barras para o re-cálculo número de barras do TF atual dentro de um dia giMinBars int (86400 PeriodSeconds () 1 st barras retângulo de intervalo completo SetIndexBuffer (0. buff1stBarOuter, INDICATORDATA) PlotIndexSetDouble (0. PLOTEMPTYVALUE. 0) SetIndexBuffer (1. buff1stBarOuterZero, INDICATORDATA) 1 bares st área interior rectângulo SetIndexBuffer (2. buff1stBarInner, INDICATORDATA) PlotIndexSetDouble (1. PLOTEMPTYVALUE. 0) SetIndexBuffer (3. buff1stBarInnerZero, INDICATORDATA) linha de sinal SetIndexBuffer (4. buffSignal, INDICATORDATA) PlotIndexSetDouble (2. PLOTEMPTYVALUE. 0) SetIndexBuffer (5. buffSignalColor, INDICATORCOLORINDEX) pendente linha de colocação da ordem SetIndexBuffer (6. buffEntry, INDICATORDATA) PlotIndexSetDouble (3. PLOTEMPTYVALUE. 0) SetIndexBuffer (7. buffEntryColor, INDICATORCOLORINDEX) linha SL SetIndexBuffer (8. buffSL, INDICATORDATA) PlotIndexSetDouble (4. PLOTEMPTYVALUE. 0) a linha TP SetIndexBuffer (9. buffTP, INDICATORDATA) PlotIndexSetDouble (5. PLOTEMPTYVALUE. 0) IndicatorSetInteger (INDICATORDIGITS. dígitos) IndicatorSetString (INDICATORSHORTNAME. 80-20 TS) Coloque a página de código de programas Para a função OnCalculate incorporada arranjar o loop para iteração sobre a corrente t Imeframes barras do passado para o futuro procurando-los para um sinal usando a função do módulo de sinal. Declarar e inicializar as variáveis ​​necessárias usando valores iniciais. Permite definir a barra de loop mais antiga para o primeiro cálculo considerando um limite de profundidade de histórico definido pelo usuário (BarsLimit). Para chamadas subseqüentes, todas as barras do dia atual (em vez da última barra) são recalculadas, uma vez que o padrão de duas barras realmente pertence ao gráfico D1, independentemente do período de tempo atual. Além disso, devemos proteger contra os chamados fantasmas: se não efetuarmos um buffer de indicadores forçados durante a reinicialização, então não mais áreas preenchidas relevantes permanecem na tela ao comutar cronogramas ou símbolos. A limpeza do buffer deve ser vinculada à primeira chamada da função OnCalculate após a inicialização do indicador. No entanto, a variável pré-calculada padrão não é suficiente para definir se a chamada é a primeira, uma vez que pode conter zero não apenas durante a primeira chamada de função, mas também quando se altera a soma de verificação. Vamos gastar algum tempo para resolver adequadamente este problema, criando a estrutura não afetada por definir a variável prevcalculated para zero. A estrutura é para armazenar e processar dados utilizados com freqüência nos indicadores: - sinalizador da função OnCalculate primeiro lançamento - o contador de barras calculadas que não é definido como zero ao alterar a soma de verificação - sinalizador de alteração da soma de verificação - sinalizador do início de Uma nova barra - hora de início da barra atual. A estrutura que combina todos estes dados deve ser declarada a nível global. Ele deve ser capaz de reunir ou apresentar dados de qualquer built-in ou funções personalizadas. Vamos nomear essa estrutura Brownie. Pode ser colocado no final do código do indicador. Um único objeto de estrutura de tipo global chamado goBrownie deve ser declarado lá também: struct BROWNIE datetime tLastBarTime tempo da última barra processada int iPrewCalculated número de barras calculadas bool bFirstRun primeiro flag de lançamento bool bHistoryUpdated history update flag bool bIsNewBar nova barra de abertura flag BROWNIE ) valores padrão: tLastBarTime 0 iPrewCalculated WRONGVALUE bFirstRun bIsNewBar verdadeira bHistoryUpdated falso vazio FRESET (bool bResetFirstRun verdadeiros) valores padrão: tLastBarTime 0 iPrewCalculated WRONGVALUE if (bResetFirstRun) bFirstRun verdadeiro set a zero se houver permissão bIsNewBar verdadeira bHistoryUpdated falsa fUpdate void (int iNewPrewCalculated WRONGVALUE ) bandeira da função built-in OnCalculate primeiro chamar if (bFirstRun ampamp iPrewCalculated gt 0) bFirstRun falsa nova datetime bar tThisBarTime TimeCurrent () - TimeCurrent () PeriodSeconds () bIsNewBar tLastBarTime tThisBarTime atualizar a hora do bar atual se (bIsNewBar) tLastBar Tempo tThisBarTime if (iNewPrewCalculated gt - 1) existem mudanças na história bHistoryUpdated iNewPrewCalculated 0 ampamp iPrewCalculated uso gt WRONGVALUE prewcalculated em caso de OnCalculate 1 chamada st if (iPrewCalculated WRONGVALUE) iPrewCalculated iNewPrewCalculated ou se não havia histórico de atualizações else if (gt iNewPrewCalculated 0) iPrewCalculated iNewPrewCalculated BROWNIE goBrownie Permite informar o Brownie do evento de inicialização do indicador: void OnDeinit (const int reason) goBrownie. fReset () informar Brownie Se necessário, a quantidade de dados armazenados pelo Brownie pode ser expandida se funções personalizadas ou As classes precisam de preços, volumes ou o valor atual do spread das barras (Open, High, Low, Close, tickvolume, volume, spread). É mais conveniente usar dados pré-fabricados da função OnCalculate e passá-los via Brownie em vez de usar as funções de cópia de série de tempo (CopyOpen, CopyHigh etc. ou CopyRates), isso economiza os recursos da CPU e elimina a necessidade de organizar o processamento de erros Dessas funções de linguagem. Vamos voltar à função de indicador principal. Declarar variáveis ​​e preparar as matrizes usando a estrutura goBrownie são as seguintes: dados de feed goBrownie. fUpdate (prevcalculated) para Brownie int iPeriodBar 0. contador auxiliar iCurrentTFBar ratestotal - int (BarsLimit) índice de barra do atual TF loop start static datetime stLastD1Bar 0 time Da última barra processada do par de barras D1 (padrões 2ª barra) static int si1stBarofDay 0 índice da barra de dias atuais primeiro se (goBrownie. bFirstRun) limpar os buffers durante a reinicialização: ArrayInitialize (buff1stBarInner, 0) ArrayInitialize buff1stBarInnerZero, 0) ArrayInitialize (buff1stBarOuter, 0) ArrayInitialize (buff1stBarOuterZero, 0) ArrayInitialize (buffEntry, 0) ArrayInitialize (buffEntryColor, 0) ArrayInitialize (buffSignal, 0) ArrayInitialize (buffSignalColor, 0) ArrayInitialize (buffTP, 0) ArrayInitialize (buffSL, 0) stLastD1Bar 0 si1stBarofDay 0 else datetime tTime TimeCurrent () profundidade mínima de re-cálculo - a partir do dia anterior: ICurrentTFBar ratestotal - Barras (Símbolo. PERIODCURRENT. TTime - tTime 86400. tTime) - 1 ENUMENTRYSIGNAL eSignal ENTRYUNKNOWN sinal duplo dSL WRONGVALUE. SL nível dTP WRONGVALUE. TP nível dEntryLevel WRONGVALUE. Nível de entrada dRangeHigh WRONGVALUE. DRangeLow WRONGVALUE bordas dos padrões 1 st intervalo de barras datetime tCurrD1Bar 0. corrente D1 bar time (padrões 2 nd bar) tD1BarToFill 0 D1 bar tempo a ser preenchido (padrões 1 st bar) certifique-se o índice de barra de re-cálculo inicial está dentro de aceitável Intervalo: iCurrentTFBar int (fmax (0.fmin (iCurrentTFBar, ratestotal - giMinBars))) enquanto (iCurrentTFBar lt ratestotal ampamp. IsStopped ()) o loop do programa principal deve ser localizado aqui Verifique a presença de um sinal ao iterar sobre a corrente (ESignal gt 1) continuam sem sinal durante o dia em que a barra pertence Se houver um sinal em uma nova barra de dias, o intervalo de A barra diária anterior deve ser preenchida. O valor da variável tD1BarToFill do tipo datetime é usado como um sinalizador. Se for igual a WRONGVALUE, nenhum preenchimento é necessário nesta barra. A linha de sinal deve começar na mesma primeira barra, mas permite estender até a última barra do dia anterior para melhor percepção de layout. Uma vez que os cálculos de uma linha de sinal, bem como linhas e cores de preenchimento para barras de alta e baixa são diferentes, permite fazer dois blocos semelhantes: tCurrD1Bar Tempo iCurrentTFBar Tempo iCurrentTFBar 86400 início do dia pertence a barra if (stLastD1Bar lt tCurrD1Bar) tD1BarToFill tempo iCurrentTFBar 1 Time iCurrentTFBar 1 86400 si1stBarofDay iCurrentTFBar outra tD1BarToFill WRONGVALUE bar dia anterior, nenhum novo enchimento necessário stLastD1Bar tCurrD1Bar lembrar se (tD1BarToFill WRONGVALUE) Encher o dias anteriores bar D1: iPeriodBar iCurrentTFBar if (dEntryLevel lt dRangeHigh) if (ShowOuter) while (- - iPeriodBar gt 0) if (Tempo iPeriodBar lt tD1BarToFill) quebrar buff1stBarOuterZeroiPeriodBar dRangeLow buff1stBarOuteriPeriodBar dRangeHigh se (ShowInner) iPeriodBar iCurrentTFBar enquanto (--iPeriodBar gt 0) if (Tempo iPeriodBar lt tD1BarToFill) quebrar buff1stBarInnerZeroiPeriodBar dRangeLow 0,2 (dRangeHigh dRangeLow) buff1stBarInneriPeriodBar dRangeHigh 0,2 (DRangeHigh dRangeLow) início da linha de sinal a partir dos dias anteriores última barra buffSignaliCurrentTFBar buffSignaliCurrentTFBar 1 dRangeLow gdExtremumBreak buffSignalColoriCurrentTFBar buffSignalColoriCurrentTFBar 1 0 else if (ShowOuter) enquanto (--iPeriodBar gt 0) if (Tempo iPeriodBar lt tD1BarToFill) quebrar buff1stBarOuterZeroiPeriodBar dRangeHigh buff1stBarOuteriPeriodBar dRangeLow se (ShowInner) iPeriodBar iCurrentTFBar enquanto (--iPeriodBar gt 0) if (Tempo iPeriodBar lt tD1BarToFill) quebrar buff1stBarInnerZeroiPeriodBar dRangeHigh 0,2 (dRangeHigh dRangeLow) buff1stBarInneriPeriodBar dRangeLow 0,2 (dRangeHigh dRangeLow) início da linha de sinal a partir dos dias anteriores última barra buffSignaliCurrentTFBar buffSignaliCurrentTFBar 1 dRangeHigh GdExtremumBreak buffSignalColoriCurrentTFBar buffSignalColoriCurrentTFBar 1 1 else continue Todas as linhas de layout restantes devem ser plotadas dentro do loop de iteração de barras de timeframes atual. Como já mencionado, a linha de sinal deve terminar na barra onde o preço tocou. A linha de ordem pendente deve começar na mesma barra e terminar na barra, na qual o contato com o preço ocorre. Tome Lucro e Stop Loss linhas devem começar na mesma barra. O layout do padrão é terminado na barra, em que o preço toca um deles: Linha de sinal até cruzada por uma barra: iPeriodBar iCurrentTFBar se (dEntryLevel lt dRangeHigh) enquanto (iPeriodBar lt ratestotal) se (Time iPeriodBar gt tCurrD1Bar 86399) quebrar buffSignaliPeriodBar dRangeLow gdExtremumBreak buffSignalColoriPeriodBar 0 if (dRangeLow gdExtremumBreak gt Baixa iPeriodBar) quebrar mais enquanto (ratestotal lt iPeriodBar) if (Tempo iPeriodBar gt tCurrD1Bar 86399) quebrar buffSignaliPeriodBar dRangeHigh gdExtremumBreak buffSignalColoriPeriodBar 1 if (dRangeHigh gdExtremumBreak lt alta iPeriodBar) A linha de introdução pausa até atravessada por uma barra de: se (dEntryLevel lt dRangeHigh) enquanto (iPeriodBar lt ratestotal) se (Tempo iPeriodBar gt tCurrD1Bar 86399) quebrar buffEntryiPeriodBar dRangeLow buffEntryColoriPeriodBar 0 if (dRangeLow lt alta iPeriodBar) se (. buffEntryiPeriodBar 1 0) começar e terminar com uma única barra, Estender por 1 bar para o passado buffEntryiPeriodBar 1 dR angeLow buffEntryColoriPeriodBar 1 0 ruptura mais tempo (ratestotal lt iPeriodBar) se (Tempo iPeriodBar gt tCurrD1Bar 86399) quebrar buffEntryiPeriodBar dRangeHigh buffEntryColoriPeriodBar 1 if (dRangeHigh gt Baixa iPeriodBar) se (buffEntryiPeriodBar 1 0.) começar e terminar com uma única barra, se estendem por uma Barra para o passado buffEntryiPeriodBar 1 dRangeHigh buffEntryColoriPeriodBar 1 1 quebrar linhas TP e SL até que um deles é atravessado por uma barra: if (dEntryLevel lt dRangeHigh) SL é igual ao Low desde o início de um dia: dSL Low ArrayMinimum (Low. si1stBarofDay, iPeriodBar si1stBarofDay) enquanto (iPeriodBar lt ratestotal) se (Tempo iPeriodBar gt tCurrD1Bar 86399) quebrar buffSLiPeriodBar DSL buffTPiPeriodBar DTP se (DTP lt alta iPeriodBar DSL gt Baixa iPeriodBar) se (buffSLiPeriodBar 1 0.) começar e terminar com uma única barra, Estender por 1 bar para o buffSLiPeriodBar passado 1 dSL buffTPiPeriodBar 1 dTP quebrar mais SL é igual ao High desde o início de um dia: dSL High ArrayMaximum (Alta si1stBarofDay, iPeriodBar si1stBarofDay) while (iPeriodBar lt ratestotal) if (Time iPeriodBar gt tCurrD1Bar 86399) quebrar buffSLiPeriodBar DSL buffTPiPeriodBar DTP se (DSL lt alta iPeriodBar DTP gt Baixa iPeriodBar) se (buffSLiPeriodBar 1 0.) começar e terminar com uma única barra, se estendem por uma barra para o passado buffSLiPeriodBar um DSL buffTPiPeriodBar 1 DTP ruptura Deixa lugar O código de chamada da função de notificação de sinal fDoAlert fora do loop. Na verdade, ele tem um pouco maiores oportunidades em comparação com os envolvidos neste indicador a função é capaz de trabalhar com arquivos de áudio significando que esta opção pode ser adicionado às configurações personalizadas. O mesmo vale para a capacidade de selecionar arquivos separados para comprar e vender sinais. Lista de funções: void fDoAlert (Função para enviar sinais e notificações string sMessage, mensagem de alerta bool bAlert true. Mostrar uma janela pop-up bool bSound false reproduzir um arquivo de som bool bEmail false enviar um eMail bool bNotification false enviar uma notificação push String sEmailSubject eMail seqüência de caracteres sSound alert. wav arquivo de som) static string ssPrevMessage houve silêncio anterior mensagem de alerta static datetime stPrevTime barra de alerta anterior time datetime tThisBarTime TimeCurrent () PeriodSeconds () PeriodSeconds () barra atual if (ssPrevMessage sMessage stPrevTime tThisBarTime) Outro andor 1 st nesta barra lembre-se: ssPrevMessage sMessage stPrevTime tThisBarTime formam uma string de mensagem: sMessage StringFormat (ssss, TimeToString (TimeLocal (), TIMESECONDS), hora local Símbolo Símbolo StringSubstr (EnumToString (ENUMTIMEFRAMES (Period) TF mensagem sMessage) ativar o sinal de notificação: if (bAlert) Alert (sMessag E) if (bEmail) SendMail (sEmailSubject Símbolo. SMessage) if (bNotification) SendNotification (sMessage) if (bSound) PlaySound (sSound) O código para verificar a necessidade de chamar a função e formando o texto para ela localizado no corpo do programa antes da conclusão do manipulador de eventos OnCalculate: alert iPeriodBar ratestotal 1 current bar if (AlertPopup AlertEmail AlertPush 0 ) return (ratestotal) all is disabled if (buffSignaliPeriodBar 0 ) return (ratestotal) nothing to catch yet (or already) if ( buffSignaliPeriodBar gt High iPeriodBar buffSignaliPeriodBar lt Low iPeriodBar ) return (ratestotal) no signal line touching message text: string sMessage StringFormat ( TS 80-20: needed ss, TP: s, SL: s , buffSignalColoriPeriodBar gt 0. BuyStop. SellStop , DoubleToString (dEntryLevel, Digits ), DoubleToString (dTP, Digits ), DoubleToString ( dSL, Digits ) ) notification: fDoAlert(sMessage, AlertPopup, false. AlertEmail, AlertPush, AlertEmailSubj) return (ratestotal) complete OnCalculate operation The entire source c ode of the indicator can be found in the attached files (TS80-20.mq5). The trading layout according to the system is best seen on minute charts. Please note that the indicator uses the bar data rather than tick sequences inside bars. This means if the price crossed several layout lines (for example, Take Profit and Stop Loss lines) on a single bar, you cannot always define which of them was crossed first. Another uncertainty stems from the fact that the start and end lines cannot coincide. Otherwise, the lines from the buffer of DRAWLINE and DRAWCOLORLINE types will simply be invisible to a user. These features reduce the layout accuracy but it still remains quite clear. Expert Advisor for testing the 80-20 trading strategy The basic EA for testing strategies from the book Street Smarts: High Probability Short-Term Trading Strategies was described in details in the first article. Lets insert two significant changes in it. First, the signal module is to be used in the indicator as well meaning it would be reasonable to set trading levels calculation in it. We have already done this above. Apart from the signal status, the feGetEntrySignal function returns order placement, Stop Loss and Take Profit levels. Therefore, lets remove the appropriate part of the code from the previous EA version adding the variables for accepting levels from the function and edit the function call itself. The listings of the old and new code blocks can be found in the attached file (strings 128-141). Another significant addition to the basic EA code is due to the fact that, unlike the previous two, this TS deals with a short-term trend. It assumes that the roll-back happens once a day and is unlikely to be repeated. This means that the robot has to make only one entry ignoring the existing signal all the rest of the time until the next day. The easiest way to implement that is to use a special flag static or global variable of bool type in the program memory. But if the EA operation is interrupted for some reason (the terminal is closed, the EA is removed from the chart, etc.), the flag value is lost as well. Thus, we should have the ability to check if todays signal was activated previously. To do this, we may analyze the history of trades for today or store the date of the last entry in the terminal global variables rather than in the program. Let us use the second option since it is much easier to implement. Provide users with the ability to manage one entry per day option and set an ID of each launched version of the robot it is needed to use global variables of the terminal level: input bool OneTrade false One position per day input uint MagicNumber 2016 EA magic number Lets add the variables necessary to implement one entry per day option to the programs global variables definition block. Initialize them in the OnInit function: string gsPrefix identifier of (super)global variables bool gbPositionToday false , gbPendingToday false Create a prefix of (super)global variable names: gsPrefix StringFormat ( SSB s u s. Symbol. MagicNumber, MQLInfoInteger ( MQLTESTER ). t . ) Has the robot worked with market or pending orders today gbPositionToday int ( GlobalVariableGet (gsPrefix LastPositionDate )) TimeCurrent () TimeCurrent () 86400 gbPendingToday int ( GlobalVariableGet (gsPrefix LastPendingDate )) TimeCurrent () TimeCurrent () 86400 Here the robot reads the values of global variables and compares the written time with the day start time, thus defining if the todays signal has already been processed. Time is written to the variables in two places lets add the appropriate block to the pending order installation code (additions highlighted): if (iTry - 10 ) if (LogLevel gt LOGLEVELNONE) Print ( Pending order placing error ) the distance from the current price is not enough :( if (LogLevel gt LOGLEVELERR) PrintFormat ( Pending order cannot be placed at the s level. Bid: s Ask: s StopLevel: s , DoubleToString (dEntryLevel, Digits ), DoubleToString (goTick. bid, Digits ), DoubleToString (goTick. ask, Digits ), DoubleToString (gdStopLevel, Digits ) ) else to update the flag: GlobalVariableSet ( in the terminal global variables gsPrefix LastPendingDate , TimeCurrent () TimeCurrent () 86400 ) gbPendingToday true in the program global variables The second block is placed after the code defining a newly opened position: if ( PositionSelect ( Symbol )) if ( PositionGetDouble ( POSITIONSL ) 0 .) if (gbPositionToday) update the flag: GlobalVariableSet ( in the terminal global vari ables gsPrefix LastPositionDate , TimeCurrent () TimeCurrent () 86400 ) gbPositionToday true in the program global variables . These are the only significant changes in the previous EA version code. The finalized source code of the new version is attached below. Strategy backtesting In order to illustrate the trading system viability, its authors use patterns detected on the charts from the end of the last century. Therefore, we need to check its relevance in todays market conditions. For testing, I took the most popular Forex pair EURUSD, the most volatile pair USDJPY and one of the metals XAUUSD. I increased the indents specified by Raschke and Connors 10 times, since four-digit quotes were used when the book was written, while I tested the EA on five-digit ones. Since there is no any guidance concerning the trailing parameters, I have selected the ones that seem to be most appropriate to daily timeframe and instrument volatility. The same applies to the Take Profit calculation algorithm added to the original rules the ratio for its calculation was chosen arbitrarily, without deep optimization. The balance chart when testing on the five-year EURUSD history with the original rules (no Take Profit): The same settings and Take Profit: The balance chart when testing the original rules on the five-year USDJPY history: The same settings and Take Profit: The balance chart when testing the original rules on the daily gold quotes for the last 4 years: The full data on the robot settings used in each test can be found in the attached archive containing the complete reports. Conclusion The rules programmed in the signal module match the 80-20 trading system description provided by Linda Raschke and Laurence Connors in their book Street Smarts: High Probability Short-Term Trading Strategies. However, we have extended the original rules a bit. The tools (the robot and the indicator) are to help traders draw their own conclusions concerning the TS relevance in todays market. In my humble opinion, the TS needs a serious upgrade. In this article, I have tried to make some detailed comments on developing the code of the signal module, as well as the appropriate robot and indicator. I hope, this will help those who decide to do the upgrade. Apart from modifying the rules, it is also possible to find trading instruments that fit better to the system, as well as signal detection and tracking parameters. FOREX Strategies Forex Strategy, Simple strategy, Forex Trading Strategy, Forex Scalping Forex Strategy 80-20 8212 another very simple and quite an interesting strategy forex Linda Raschke (previously we looked at 2 of its strategy: Turtle Soup, Turtle Soup plus One ), in which trade is conducted only on the daily range (D1) and trading signals are only During the 1 st trading day. Investigating the patterns of financial markets, it was noted that if the price on the market closes at the top or bottom 10 -20 of its daily range, then there is a possibility and it is 80 -90, the next morning, the price will continue to move in the same direction (ie towards the closing day candles), but eventually the price closes above or below this candle in only 50 of cases . That8217s a given fact (a chance to turn in the middle of the 2 nd day after the close of the 1 st day candles), and allowed 80-20 strategy exist and be popular in the financial markets. So, let8217s look at how deals are made in Forex Strategy 80-20 . an example of the transaction on the purchase . Suppose we open a trading terminal MetaTrader 4 today and note that: 1) Yesterday8217s daily candle was discovered in the upper 20 of its daily range and closed in the bottom 20 of its daily range. Ie If the daily candle divided into 5 parts, the opening price of yesterday8217s daily candle is in the top 1 5 of a closed candle. And the closing price is at the bottom 1 5 of the closed day candles. Figure 1. Dedicated bearish candle was discovered in 1 5 of the upper range and closed at 1 5 of its lower range 2) Today8217s daily candle opens and the price at the market went in the same direction as the close of the previous daily candle 8212 ie for sale, presumably for at least 10-15 points. 3) At this moment, when the price is already below yesterday8217s low and we have clearance to be placed pending order, we set the pending order to buy the type Buy Stop at yesterday8217s low price Figure 2. This is the same candle as in Figure 1, only the hourly interval. Expose the pending order to buy at a time when the price of the 2 nd hour candle falls below yesterday8217s low. 4) After the opening of trading positions in the purchase, we will establish a safety stop-loss orders below a few points (3-5) segodneshnego minimum. 5) Next, use a trailing stop (Universal trailing stop. the standard in Metatrader 4, or a trailing stop on the 1 st paragraph ) to lock in profits and tightens our stop-loss at a safe distance that you define for themselves, depending on the the chosen currency pair and the volatility in the forex market. For example, if the amount of daily candles 100-200 points, and trailing stop should be placed at a distance 50-70-100 points. Candle 50-70 points 8212 tryling-stop: 25-30 points. 6) If you prefer, you can put a profit target at a distance of at least 3.2 times the initial stop-loss (as required by our Money Management Forex ). Or record profits on the important Fibonacci levels. built by the first candle (38,2, 61,8) 7) Or you can simply rearrange the position of zero level. as soon as you see fit and leave the deal by the end of the trading day, and then look to close it or leave open. But I personally believe that it is better to use a trailing stop to lock in profits. For transactions on sale 8212 the rules of the opposite Figure 3. Vystalyaem pending order to sell Sell Stop, when the price broke yesterday makismum. Stop-loss is 10-15 points higher than this maximum, because price is not too moved away from him and turned around. Note: The transactions in this strategy are not as common, but if you observe the laws of several currency pairs, the probability of the conditions and the entry into the market will garazdo above By this strategy, forex trading you can buy Note: if you want to receive updates Expert Advisor - LEAVE positive feedback in the store Plati. ru without specifying e-mail in the body of reviews e-mail please indicate on the payment page 8212 which indicates where the goods will be delivered Subject to strict adherence to rules of the forex strategy 80-20, we get approximately the following trading results ( test results Adviser 80-20 strategy ): 1) Test strategies forex 80-20 8212 EURUSD (D1) with Expert Advisor 80-20 strategy 2) Test strategies forex 80-20 8212 EURJPY (D1) with Expert Advisor 80-20 strategy 3) test strategies forex 80-20 8212 USDCAD (D1) with Expert Advisor 80-20 strategyForex Strategy 80-20 - another very simple and quite an interesting strategy forex Linda Raschke (previous ly we looked at 2 of its strategy: Turtle Soup, Turtle Soup plus One ), in which trade is conducted only on the daily range (D1) and trading signals are only During the 1 st trading day. I recommend selecting a Broker Forex with Terminal MetaTrader 4 . Investigating the patterns of financial markets, it was noted that if the price on the market closes at the top or bottom 10 -20 of its daily range, then there is a possibility and it is 80 -90, the next morning, the price will continue to move in the same direction (ie towards the closing day candles), but eventually the price closes above or below this candle in only 50 of cases . Thatrsquos a given fact (a chance to turn in the middle of the 2 nd day after the close of the 1 st day candles), and allowed 80-20 strategy exist and be popular in the financial markets. So, letrsquos look at how deals are made in Forex Strategy 80-20 . an example of the transaction on the purchase. Suppose we open a trading terminal MetaTrader 4 today and note that: 1) Yesterdayrsquos daily candle was discovered in the upper 20 of its daily range and closed in the bottom 20 of its daily range. Ie If the daily candle divided into 5 parts, the opening price of yesterdayrsquos daily candle is in the top 1 5 of a closed candle. And the closing price is at the bottom 1 5 of the closed day candles. Figure 1. Dedicated bearish candle was discovered in 1 5 of the upper range and closed at 1 5 of its lower range 2) Todayrsquos daily candle opens and the price at the market went in the same direction as the close of the previous daily candle - ie for sale, presumably for at least 10-15 points. 3) At this moment, when the price is already below yesterdayrsquos low and we have clearance to be placed pending order, we set the pending order to buy the type Buy Stop at yesterdayrsquos low price Figure 2. This is the same candle as in Figure 1, only the hourly interval. Expose the pending order to buy at a time when the price of the 2 nd hour candle falls below yesterdayrsquos low. 4) After the opening of trading positions in the purchase, we will establish a safety stop-loss orders below a few points (3-5) segodneshnego minimum. 5) Next, use a trailing stop (Universal trailing stop. the standard in Metatrader 4, or a trailing stop on the 1 st paragraph ) to lock in profits and tightens our stop-loss at a safe distance that you define for themselves, depending on the the chosen currency pair and the volatility in the forex market. For example, if the amount of daily candles 100-200 points, and trailing stop should be placed at a distance 50-70-100 points. Candle 50-70 points - tryling-stop: 25-30 points. 6) If you prefer, you can put a profit target at a distance of at least 3.2 times the initial stop-loss (as required by our Money Management Forex ). Or record profits on the important Fibonacci levels, built by the first candle (38,2, 61,8) 7) Or you can simply rearrange the position of zero level. as soon as you see fit and leave the deal by the end of the trading day, and then look to close it or leave open. But I personally believe that it is better to use a trailing stop to lock in profits. For transactions on sale - the rules of the opposite Figure 3. Vystalyaem pending order to sell Sell Stop, when the price broke yesterday makismum. Stop-loss is 10-15 points higher than this maximum, because price is not too moved away from him and turned around. Note: The transactions in this strategy are not as common, but if you observe the laws of several currency pairs, the probability of the conditions and the entry into the market will garazdo abovBy this strategy, forex trading you Expert Advisor to the 80-20 strategy Subject to strict adherence to rules of the forex strategy 80-20, we get approximately the following trading results ( test results Adviser 80-20 strategy ): 1) Test strategies forex 80-20 - EURUSD (D1) with Expert Advisor 80-20 strategy 2) Test strategies forex 80-20 - EURJPY (D1) with Expert Advisor 80-20 strategy 3) test strategies forex 80-20 - USDCAD (D1) with Expert Advisor 80-20 strategy

No comments:

Post a Comment