воскресенье, 6 мая 2018 г.

Forex inválido sl ou tp


S / L ou T / P inválidos em 4, para ordens do mercado. Qualquer preço. Não posso colocar qualquer ordem.


WHRoeder Eu estou começando a pensar que você tem esse código sentado em um documento de texto em sua área de trabalho, sempre pronto para copiar e colar. ;) Eu uso eu mesmo, embora eu tenha mudado isso. Eu coloco na minha função init (), seguida por.


WHRoeder Eu estou começando a pensar que você tem esse código sentado em um documento de texto em sua área de trabalho, sempre pronto para copiar e colar.


Eu mesmo uso, embora tenha mudado. Eu coloco na minha função init (), seguida por.


TP / SL são os preços (pips2dbl), o escorregamento está em pontos (pips2points). Hã? Duh! Correção de código:


. e eu não uso o Digits. pips.


Peguei vocês. Obrigado pelas dicas. Até agora, minha única experiência é com o testador, então meu código estava funcionando como eu esperava.


Quando você fala sobre isso.


Cada mudança de parâmetro / TF / par ou uma atualização de gráfico executará um ciclo de inicialização / inicialização.


. Eu percebo que há algumas coisas importantes que eu não entendo sobre 4. Como uma atualização de gráfico acontece? E como os 3 primeiros eventos que você menciona ocorrem sem o EA sendo descarregado e recarregado? Há circunstâncias em que os globals saem do escopo, mas os externos não?


A atualização acontece via clique direito & gt; atualizar. Possivelmente após uma conexão perdida / relogin.


Os eventos não recarregam o EA, eles só chamam deInit / init. Para recarregar um EA, você deve removê-lo do gráfico e reconectá-lo. Isso redefine os globals.


Se você fechar e reiniciar o terminal, você está recarregando o EA para que os globals sejam redefinidos, os externos serão redefinidos para os últimos valores salvos (valores de configuração da GUI, não modificações internas).


Qual é o ponto em um global com um valor constante. Use #define em vez disso.


Um global com um valor calculado deve ser inicializado. No init se constante, no começo, se não. & quot; Global * = 10; & quot; não é uma inicialização, é uma modificação.


Externs são definidos com seus valores iniciais antes do init, somente leitura, não os modifique.


Qual é o ponto em um global com um valor constante. Use #define em vez disso.


Um global com um valor calculado deve ser inicializado. No init se constante, no começo, se não. & quot; Global * = 10; & quot; não é uma inicialização, é uma modificação.


Externs são definidos com seus valores iniciais antes do init, somente leitura, não os modifique.


Bem, eu não uso globals para constantes. Para esclarecer minha pergunta:


Por que o stoploss ou o lucro são inválidos?


Eu sou novo em negociação e estou tentando em torno de uma conta de prática depois de ter assistido / ler os artigos de estratégia de iniciante de forex.


O que estou fazendo de errado aqui?


Eu acho que o seu SL e TP e entrada são muito próximos uns dos outros. Geralmente você precisa deixar 1-2 pips (10-20 pontos) de distância entre cada um deles. Portanto, se a sua entrada de compra é 99,90, o seu SL deve estar abaixo de 99,88 o seu TP acima de 99,92. Tente se funciona.


Edit: até 50.000 / 150.000 não funciona.


"O preço de abertura definido deve diferir do preço de mercado em pelo menos 80 pips"


No momento da captura de tela, você tinha spreads bastante grandes. Você está tentando configurar um Sell Stop, que significa vender a preços menos favoráveis ​​a 0,685 8, mas o preço de oferta já está em 0,685 0. Então, teoricamente (o corretor pode não permitir negociar dentro de um pequeno intervalo) você deve usar um limite de venda em 58 ou um ponto de venda abaixo de 50.


Espero que ajude.


Obrigado pela ajuda.


Pode haver muitas razões pelas quais você recebe o erro:


você não selecionou o tipo certo de pedido pendente.


Como colocar stop loss e tomar lucros usando uma estratégia máxima.


Ao entrar em uma negociação, como você escolhe o ponto do stop loss e obtém lucro? Claramente, essa decisão terá um impacto sobre a lucratividade de seus negócios. No entanto, você sabia que a colocação dos níveis de saída do youdr pode realmente ter mais influência sobre sua lucratividade do que a decisão sobre a direção a ser negociada?


No volátil mercado Forex, é verdade. Dado o quão importante é essa decisão, é surpreendente o quão pouco pensamento muitos comerciantes dão a este componente de seu comércio.


Neste artigo, quero explicar uma estratégia quantitativa que ajudará você a selecionar paradas e obter níveis de lucro para o lucro máximo. Eu também quero desmascarar alguns dos equívocos comuns sobre configurações de recompensas de risco, e mostrar como seguir um conselho ruim pode arruinar um sistema de negociação potencialmente bom.


Se você quiser apenas testar a calculadora de perda de parada / lucro, e não estiver interessado na teoria, clique aqui.


Por que adivinhar parar perdas e tomar lucros é um plano para o fracasso.


Uma posição de negociação normalmente sairá em um dos dois pontos. Depois de entrar no comércio, quer:


O preço atinge o take profit (TP), e o trade termina em lucro. O preço chega ao stop loss (SL), e a trade acaba com uma perda.


Ao decidir as saídas comerciais, às vezes é tentador fazer um palpite. Alguns comerciantes usam recursos técnicos, como velas, tendências, resistências e suportes. Outros simplesmente escolhem uma taxa fixa de meta de lucro para parar a perda.


Embora isso seja muito comum, existem várias desvantagens:


É propenso a erros. Quando você adivinha os níveis de saída de um negócio, é muito fácil superestimar ou subestimar os movimentos de preços. Não é repetível e isso torna muito difícil analisar ou melhorar o desempenho. Quando não há lógica ou metodologia por trás das colocações de pontos de saída, você nunca sabe se uma falha ocorreu devido a uma combinação TP / SL mal calculada ou porque sua estratégia não está funcionando. Os traders frequentemente mudam para cima ou para baixo nos negócios subsequentes, com base em tentativa e erro, tentando encontrar um “ponto ideal”. É muito difícil automatizar métodos que dependam do instinto ou de outras decisões subjetivas.


Não há nada de errado em usar a análise técnica como um guia para cronometrar a entrada comercial, nem para julgar até que ponto o preço pode se mover. Em vez disso, o método que descrevo abaixo é usado juntamente com os gráficos e a análise fundamental.


A falácia de usar o SL / TP como recompensa de risco de proxy.


Fóruns de negociação Forex estão cheios de conselhos bem-intencionados, mas um tanto equivocados sobre configurações de risco-recompensa e como definir suas perdas de parada. Infelizmente, muitas dessas pessoas não entendem o verdadeiro significado de risco ou recompensa.


A idéia de que simplesmente definir sua perda de parada menor do que os seus lucros obterá uma certa recompensa de risco é um absurdo completo.


Usar risco / recompensa para definir sua entrada comercial e saídas não faz sentido a menos que você saiba a probabilidade de resultados em um determinado negócio.


Tome este exemplo simples. Suponha que haja uma loteria custando US $ 1 para entrar. O prêmio é de US $ 1 milhão. Pela definição do comerciante ingênuo, isso dá:


Relação recompensa / risco: 1.000.000.


Por essa definição, isso parece um jogo fantástico para jogar. No entanto, suponha que saibamos que dois milhões de pessoas entram na loteria. Isso faz com que as chances de ganhar 1: 2,000,000 (um em dois milhões). Agora sabemos as probabilidades, podemos calcular a verdadeira recompensa de risco:


Em outras palavras, para cada $ 1 que você colocar nessa loteria, espere receber 50 centavos de dólar de volta. A maioria concordaria agora que este não é um jogo muito bom. Mesmo que, na conta do comerciante ingênuo, ele tivesse uma taxa de risco de recompensa de um milhão.


Este exemplo destaca a falácia de usar stops e obter lucros como uma medida do seu risco / recompensa.


Em uma negociação, temos o risco / recompensa real definido por:


E (vitória) é a recompensa esperada no negócio, ou seja, o valor do seu lucro. E (perder) é o seu valor de stop loss.


A Relação Risco-Recompensa


A primeira coisa a se perceber sobre a definição de pontos de saída de negociação é que a quantidade de lucro que você deseja fazer em uma negociação é diretamente proporcional ao risco que você precisará correr para capturar esse lucro.


Isto não é uma suposição, mas sim um fato matemático.


Tome o seguinte cenário de negociação. Digamos, por exemplo, que um trader veja uma tendência ascendente no gráfico horário para o USD / JPY (veja gráfico abaixo). A tendência está em vigor há cerca de um dia, então o trader acredita que há uma boa oportunidade de lucro.


Ele decide a seguinte configuração:


Agora vamos analisar essa configuração de negociação em mais detalhes. A primeira coisa a notar é o comerciante quer capturar um lucro de 70 pips no comércio.


Então, o que há de errado com essa configuração?


Com base nos dados de preços recentes para este par de moedas, podemos calcular que o USD / JPY tem uma volatilidade horária de 26,4 pips. Isso significa que, em média, o movimento do preço em uma hora é de 26,4 pips. Às vezes mais, às vezes menos, mas essa é a média.


Isso significa que o comerciante está tentando lucrar em 70 pips. Na realidade, ele está realmente apostando contra o mercado porque está confiando no fato de que o preço não descerá mais de 20 pips do preço aberto durante a vida do negócio. Isso pode levar até 30 horas se a tendência atual continuar (da Figura 1).


Conselheiro de Stop Loss.


Indicador Gráfico.


Escolher a colocação de perda de parada certa é uma decisão crítica, mas muitas vezes é deixada ao acaso. Esta ferramenta Metatrader aconselha onde colocar paradas e obter lucros em qualquer ordem. Basta definir o tempo de troca desejado e a taxa de ganho e o indicador faz o resto.


Dada a volatilidade horária em USD / JPY está atualmente acima de 26 pips, essa estabilidade no preço seria altamente improvável. Enquanto o trade tem uma perda máxima muito baixa (20 pips), o que pode parecer uma vantagem, as chances de terminar em lucro são extremamente baixas.


Se sabemos, em média, que o preço do USD / JPY sobe ou desce 26,4 pips a cada hora, por que faria algo diferente para esse negócio em particular? A resposta é que isso não aconteceria e o comércio provavelmente atingiria o stop loss por esse motivo.


Devido à volatilidade no FX, isso é verdade mesmo se a tendência prevista continuar.


O problema básico com a configuração era que o comerciante estava tentando capturar muito lucro sem contabilizar a volatilidade.


Lembre-se de que, no Forex, a volatilidade não é algo que você pode evitar escolhendo cuidadosamente o comércio ou uma estratégia inteligente. É uma certeza absoluta.


É por isso que é muito melhor fazer a volatilidade funcionar para você e não contra você.


A questão, então, é quando se estabelece uma negociação, como você sabe onde colocar os pontos de saída além de apenas adivinhar? A seguir, explicarei como fazer isso.


Calculando Stop Losses e Take Profits Usando Maximals.


O método que eu prefiro usar é baseado em uma técnica conhecida como maximals. O que isto faz é dar uma fórmula precisa para calcular a probabilidade de o preço se mover a uma certa distância da abertura durante um determinado tempo.


Este modelo fornece uma distribuição completa dos movimentos de preço para uma dada volatilidade. Este método funciona para qualquer período de tempo, minutos, horas ou até meses. Também funciona igualmente bem com volatilidade histórica (passada) ou implícita (futura).


Ao decidir os pontos de saída do comércio, há três coisas a serem consideradas:


O cronograma esperado do comércio (relacionado à meta de lucro) O comportamento de tendência de mercado A meta de lucro.


Vamos dar uma olhada em cada um deles.


Etapa 1: o período de tempo.


O tipo de trader que você é terá um impacto sobre o tempo que seus negócios precisam ficar abertos para atingir sua meta de lucro.


Um day trader ou um scalper manteria uma posição por horas, minutos ou até segundos. No outro extremo, um operador de carry mantém posições por semanas ou meses. Para o operador de carry, o ganho de capital no comércio é geralmente menos importante. O objetivo é manter a posição aberta pelo maior tempo possível para acumular juros.


Claramente, então, lucro e tempo estão ligados. Portanto, ao definir seus pontos de saída de negociação, o primeiro passo é saber com precisão até que ponto o preço provavelmente se moverá em um determinado período de tempo. Depois de saber disso, você poderá decidir uma meta de lucro realista.


Tome o seguinte exemplo. A figura 2 abaixo mostra o EUR / USD em intervalos de cinco minutos (M5). O gráfico abrange um período de 24 horas.


A primeira coisa que faço é calcular a volatilidade durante o período escolhido. A partir dos dados de abertura / fechamento, calculo que seja um pouco mais de 10 pips por período de 5 minutos.


Uma vez que sei quão volátil é o mercado, posso projetar o preço para frente para calcular a probabilidade de um determinado movimento x horas (definido por intervalos de 5 minutos) no futuro.


Para fazer isso, preciso calcular o que é conhecido como curvas máximas (veja a caixa para uma explicação). Resumidamente, tomando a volatilidade como entrada, essas curvas me dirão a probabilidade de um preço máximo (seja para cima ou para baixo) ser atingido.


A Figura 3 abaixo mostra as curvas máximas calculadas para 1 hora a 24 horas à frente para o gráfico EUR / USD.


Por exemplo, olhando para a curva máxima por 24 horas (top line), eu sei que o preço tem uma probabilidade de 76,8% de se mover 62 pips dentro de um período de 24 horas. Considerando que tem uma probabilidade de 40% de mover mais de 141 pips no mesmo período de tempo.


O passeio aleatório


Eu só dou uma breve descrição aqui do que são cálculos bastante complexos. O melhor modelo de mercado que temos para forex é o processo aleatório de passo ou passeio aleatório.


Isso significa apenas que, a cada intervalo, o mercado se move por um valor de etapa aleatório. O preço pode inclinar-se para uma tendência de alta ou uma tendência de baixa com um parâmetro de desvio.


Em essência, quanto maior o intervalo de tempo e maior a volatilidade, mais o preço pode se mover a partir do nível existente.


Destes podemos calcular a probabilidade de uma alteração de preço ao longo de qualquer período de tempo.


Os fundos de hedge e os operadores profissionais geralmente usam curvas máximas ou alguma variante delas. A razão pela qual eles são tão importantes é que eles permitem que você configure seu comércio com precisão em termos de tempo e captura de lucros. A curva informa se a quantia de lucro que você deseja fazer é razoável em termos do período de tempo.


Por exemplo, eu sei que se eu quisesse capturar um movimento de 300-pip, eu provavelmente estaria esperando aproximadamente dez dias com base no atual nível de volatilidade. Isso ocorre porque, da curva, há apenas 10% de chance de o preço subir 300 pips em qualquer período de 24 horas.


Etapa 2: o mercado.


Se o mercado for plano ou tender em uma certa direção, isso terá forte influência sobre onde você coloca suas paradas e lucros. Em termos de modelo, significa que temos uma distribuição assimétrica dos movimentos de preços.


Existem várias maneiras de permitir isso, mas a mais simples e a que eu prefiro é usar uma volatilidade diferente para o modelo de preço de alta e baixa.


O desvio estatístico é útil aqui porque informa como a distribuição da volatilidade é assimétrica e permite que você adicione um desvio para cima / para baixo.


Caminhada aleatória - não tendendo.


Tendência para cima - desvio positivo.


Tendência para baixo - desvio negativo.


Com a caminhada aleatória, os movimentos de subida e descida de preços são igualmente prováveis. Quando tendências, dois conjuntos diferentes de curvas máximas são necessários, um para movimentos para cima e outro para baixo.


Etapa 3: O objetivo do lucro.


Tendo decidido sobre um cronograma e as características da tendência, agora posso escolher uma meta de lucro apropriada que dará ao meu negócio uma alta probabilidade de ganho.


Digamos que eu verifiquei o gráfico e decidi comprar no nível atual do mercado, e decido que meu alvo será de +40 pips e meu corte será de -100 pips.


A tabela abaixo mostra a probabilidade de meus pontos de saída serem atingidos em cada uma das três condições de mercado.


Tendência +: Tendência na mesma direção.


Tendência & # 8211; : Tendência inverte a direção.


Apartamento: mercado de Sideways.


Minha configuração de comércio é então:


Leve lucro +40 pips 82% probabilidade de alcançar o TP dentro de 24 horas.


Stop loss -100 pips 57% de probabilidade de alcançar o SL em 24 horas.


O que esta análise me diz é que o EUR / USD tem uma certa chance de alcançar os níveis TP / SL dentro do meu tempo de negociação. Mas isso não me diz qual é alcançado primeiro.


O que eu também gostaria de ver é a probabilidade de o comércio realmente ter lucro ou prejuízo. O preço pode chegar primeiro ao stop e depois ao take profit. Nesse caso, minha negociação terminaria com uma perda. Alternativamente, ele poderia alcançar o take profit primeiro, caso em que ele ganha. Alternativamente, ele não pode alcançar a parada nem ter nível de lucro, caso em que o negócio permanece aberto.


Com base nessa análise, posso usar a teoria da probabilidade padrão para calcular cada resultado para o negócio:


Meu melhor resultado acontece se a tendência de curto prazo se reverter, isto é, se o mercado subir e tornar minha compra lucrativa. O pior resultado acontece se a tendência continuar na mesma direção (tendência +). Nesse caso, tenho 42% de chance de o trade terminar em lucro e 47% de chance de terminar em prejuízo.


Quando defino o que estou procurando, é a chance de o lucro ser atingido ser, pelo menos, 1,5x a chance de a parada ser alcançada. Isso dará uma taxa de vitória de cerca de 70% ou mais.


Além disso, lembre-se de que, se você mover o stop loss ou tomar lucro enquanto a negociação estiver aberta, isso resultará em um conjunto totalmente diferente de resultados.


Analisando o comércio.


Para ver como os níveis de stop e take profit mudam para diferentes prazos de negociação, posso calcular um envelope, o que me dará uma taxa de ganho fixa. O gráfico abaixo na Figura 4 mostra isso plotado para o comércio do meu exemplo.


A partir disso, posso ver que, se eu estivesse negociando em um período de 12 horas, poderia escolher definir:


Isso alcançaria o mesmo índice de vitórias. Também daria um lucro menor de apenas 26,9 pips.


Com o meu prazo de 24 horas, também posso ver como os resultados possíveis vão mudar ao longo do tempo.


O gráfico abaixo (Figura 5) mostra a probabilidade de uma vitória, uma perda ou a negociação que permanece aberta por mais de 24 horas & # 8211; o tempo de vida esperado do meu comércio.


Do gráfico, vejo que ele tem a maior chance de obter lucro nos primeiros 90 minutos de abertura. Depois disso, a chance de uma perda aumenta significativamente.


Isso ocorre porque as curvas máximas se tornam mais planas por períodos mais longos. Se você verificar a Figura 3 novamente, verá que as curvas de 24 horas e 18 horas são bastante semelhantes, ao passo que há uma grande diferença entre as curvas de 1 hora e 6 horas. O maior diferencial está nos primeiros intervalos em que as curvas são mais íngremes.


Finalmente, dados os dados acima, a expectativa futura pode ser calculada para encontrar o retorno esperado do lado da compra e do lado da venda.


Gerenciamento de dinheiro.


Como mostrado acima, suas distâncias de parada precisam funcionar em termos de sua meta de lucro e dos níveis de volatilidade.


Os novos operadores muitas vezes colocam as perdas de parada muito apertadas, achando que estão reduzindo o risco. A razão usual para isso é que eles estão usando muita alavancagem e tentam reduzir a exposição, colocando limites em negociações individuais. É melhor gerenciar o risco por meio do tamanho do comércio (exposição) do que usar as perdas de parada que não fazem sentido.


Suponha que você veja uma oportunidade de negociação, e o rebaixamento potencial precisa ser de 300 pips para capturar esse lucro. Se 300 pips não é uma perda aceitável, então é melhor reduzir a alavancagem e ajustar o tamanho do seu negócio para baixo para lhe dar mais flexibilidade.


Em vez de negociar um lote, considere negociar em um décimo de várias unidades ou menos.


O que é mais importante é que uma perda potencial (ou valor de saque) em uma negociação deve ser gerenciável em sua conta. Isso deve ser parte de uma estratégia geral de gerenciamento de dinheiro para que você saiba os seus limites de perda e essas perdas, mesmo em sucessão não causará uma chamada de margem ou sua conta falida.


Lembre-se, o excesso de alavancagem é o assassino # 1 dos novos comerciantes forex.


Calculadora de Stop Loss.


Eu forneço a planilha do Excel com todos os cálculos aqui para que você possa baixá-la e experimentar este sistema por si mesmo.


Para instruções sobre como usar a folha, por favor veja aqui. A planilha não tem o feed de preço real que o indicador 4 usa, mas você pode colar manualmente os dados de preços históricos de para calcular o lucro ideal e interromper as perdas da mesma maneira que eu expliquei.


O indicador, que faz os mesmos cálculos em tempo real e inclui recursos adicionais, também está disponível. Veja abaixo para mais detalhes.


Gostaria de se manter informado?


Negociar sem parar perdas pode soar como a coisa mais arriscada que existe. Um pouco como ir montanhismo. Como aproveitar ao máximo os tipos de pedidos de Forex.


Ordens são muitas vezes vistas como nada mais do que um show paralelo ao negócio real da negociação. Ainda o intervalo. Valor em risco: como calcular o risco de Forex.


Para gerenciar esse risco, o que alguns fazem é supor uma estimativa simples para estimar a perda potencial envolvida. Por que a maioria das estratégias de linha de tendência falha?


As tendências são todas sobre o timing. Tempo-los bem, você pode potencialmente capturar um movimento forte no mercado. Day Breakouts Volume de Negociação.


Essa estratégia funciona detectando breakouts no EURUSD nos momentos em que o volume está aumentando acentuadamente. Geralmente. O Engulfing Candlestick Trade & # 8211; Quão confiável é isso?


Você pode ter visto que há inúmeros artigos na web declarando engolfando estratégias são uma certeza. Estratégia de fuga do canal Keltner.


A maneira clássica de trocar o canal Keltner é entrar no mercado à medida que o preço quebra acima ou abaixo.


Obrigado por esta abordagem incrível de toda esta teoria sl / tp. Depois de usar a abordagem r / 2r (simplesmente colocando sua perda de parada na metade da distância do seu tp) por um tempo, eu já concluí que isso só funciona se você escolher a direção certa, tornando isso útil apenas para ações um pouco previsíveis. No forex, no entanto, eu já cheguei à conclusão de que a distância até o ponto de entrada é mais importante do que a direção (já que o forex parece um pouco mais imprevisível). Primeiro pensei que a chance de minha negociação atingir uma distância x dupla aumenta exponencialmente, mas isso me fez ter muitos lucros pequenos (o que ainda é lucro, mas não muito eficiente). Sua abordagem é muito lógica e você mostra os números que fazem sentido. Obrigado. Uma pergunta permanece e você parece ser o cara certo para perguntar isso: como você determina a tendência de um casal de forex? Você assiste a uma tendência de longo prazo, uma tendência de dia ou uma tendência de hora em hora que você usa uma relação calculável para o tempo esperado que você precisa para acertar suas saídas?


Eu tenho dificuldade em reproduzir seus resultados.


Eu tento calcular a menor curva -1HRS na Fig3.


Eu uso seus dados da Fig2 & # 8211; time step-5min com volatilidade 10 pips.


De acordo com a equação na caixa:


para distância 0 pips eu recebo P (Y12 = 0) = ((FATO (12) / ((2 ^ 12) * FATO (6) * FATO (6))) * 100 = 22,56%


para a distância m = 2 (20pips) eu recebo P (Y12 = 2) = (FACT (12) / ((2 ^ 12) * FACT (7) * FACT (5))) * 100 = 19.34%


Não sei exatamente a que resultados você está se referindo. Para chegar ao resultado final, há uma cadeia de probabilidades que deve ser calculada através de cada fatia de tempo.


Os exemplos mostrados foram feitos para o EURUSD, com um conjunto particular de parâmetros naquele momento.


Obrigado pelo papel interessante.


Você pode compartilhar como você calcula as volatilidades de alta e baixa?


Seu indicador Stop Loss / Take Profit usa o mesmo modelo estatístico de distribuição de preço para cálculos de probabilidade como o demo de planilha do Excel ou um mais complexo?


Não, eles são diferentes, por favor, veja as respostas anteriores sobre o mesmo.


Muito obrigado por seu stoploss / take info info. Eu estou usando um telefone Android e também baixei a calculadora sl / tp, mas não consigo encontrar os recursos que eu preciso do meu metatader android. Como posso fazer isso?


Obrigado por seus artigos, isto particularmente e a planilha que é uma ótima ferramenta na minha opinião.


Eu precisaria apenas de uma pontualização: na planilha & # 8220; Proc & # 8221 ;, a célula & # 8220; Preço atual & # 8221; é usado apenas para calcular os níveis de TP e SL, certo? Eu tentei entrar com preços muito diferentes, mas nada muda nos resultados da probabilidade de ganhar / perder, ecc., Apenas os níveis SL / TP são recalculados. A minha pergunta é: agora no EURUSD, por exemplo, estamos no limite superior de um canal fortemente ascendente; se eu comprar agora, como a taxa de vitórias pode ser a mesma no mesmo período de tempo, como se eu comprasse no meio do canal ou no limite inferior?


Obrigado pela sua resposta amável.


A planilha é apenas uma demonstração simplificada e não aceita nenhum dos feeds de dados ativos que o indicador faz.


obrigado por este ótimo post. Eu me sinto muito confiante sobre isso.


Eu sei que poucos anos se passaram desde a sua escrita, mas eu tenho uma pergunta: On & # 8216; Proc & # 8217; folha (D, 34) você tem uma constante fixa de 0,85 & # 8211; Há algo de mágico nisso? Talvez a minha pergunta seja fora do sentido, e eu realmente sinto muito se é.


Este valor não é usado em nenhum lugar da planilha.


Por que estou diminuindo & # 8220; Defina o lucro em & # 8221; que o preço de compra? Eu estou experimentando e definindo diferentes valores de preço, mas não importa o que & # 8211; Estou obtendo lucro que não seria realmente lucrativo. Aqui está o que eu vejo:


Eu tenho meu próprio sistema para usar o stop loss. Eu sempre uso taxas de fibro e nunca defini qualquer nível menor do que o nível de pivô do dia. Isso funciona na maioria das vezes.


Ótimo post obrigado.


Pensamento muito razoável e bem apoiado. Mas pelo que entendi que seria aconselhável no exemplo específico, seria abrir o com essa configuração de SL / TP e fechá-lo com uma perda ou bloqueio de lucros após 90 min a 1 hora, já que após esse período de tempo, o aumento probabilidade de acertar o SL aumentará dramaticamente. O que você acha?


Sim, é exatamente correto que a probabilidade de a parada ou o lucro ser atingido seja muito maior depois de um grande movimento & # 8211; essas probabilidades estão mudando a cada segundo. Seria uma decisão da estratégia ser usada para mover as paradas ou fechar como esse ponto.


E se eu quiser ter um lucro ilimitado? por exemplo eu invisto 300 em XRP e atinge 3000 usd. meu lucro é 2700 sobre o investimento original de 300, então meu máximo é 5700. existe uma maneira de ter um lucro ilimitado se eu quiser continuar deixando meu XRP crescer? E se eu quiser que isso cresça até atingir 1 milhão? Etoro vai me deixar fazer isso?


Oi Steve & # 8211; Ótimo artigo! Você poderia, por favor, informar como a recompensa: o risco é calculado. Eu sou novato e até agora eu estava calculando recompensa: risco apenas dividindo TP pips / SL pips, mas aprendi que não é certo depois de ler o seu artigo. Eu não sou capaz de obter a figura matemática mostrada na planilha do excel para a proporção de vitórias alvo que eu selecionei. Você poderia também mostrar com um exemplo de como o comércio de probabilidades ganha e as perdas de comércio de probabilidade são calculados. Muito obrigado.


Eu gosto muito do seu artigo. Eu estou querendo saber, você tem uma planilha para calcular as curvas máximas? Como na Figura 3. Eu baixei o arquivo de excel do Stop Loss Calculator, mas este não está lá, ou pelo menos não consigo vê-lo.


Esse gráfico é de uma planilha diferente. Pode ir em uma das ferramentas online em algum momento.


Olá Steve. Eu estava procurando uma solução para o posicionamento Stop Loss e me deparei com o seu artigo. Obrigado pelo que parece ser uma ótima solução. Eu não uso 4, mas consegui exportar o dat histórico. Meu único desafio é que não posso colar os dados nas colunas fornecidas, pois as células estão protegidas. Como faço para contornar isso? Ou seja, posso obter a senha?


Uma senha não é necessária. Isso acontece quando você está colando em muitas linhas para o intervalo. Basta recortar as linhas para o número máximo permitido e deve ficar bem.


Oi Steve, espero que você esteja bem 🙂 indicadores impressionantes & # 8211; Eu amo como tudo é matematicamente explicado e faz muito sentido! (Eu tenho um fundo de matemática / engenharia). Já comprei alguns dos indicadores e procuro o meu próximo para comprar 🙂


Para este indicador Stop Loss / Take Profit, há algum motivo para 288 períodos terem sido usados ​​para gerar as saídas?


Eu acho que a maioria das tendências nos pares que negocio se movem em 20-30 ciclos de período, então eu uso isso como o período de amostragem para que eu possa por exemplo exibir um gráfico de 15 min e ter um valor SLTP que coincida período e tem que consultar o prazo mais curto para os valores SLTP). Isso é um período muito curto?


O que seria legal seria se valores SLTP de período de tempo mais curtos pudessem ser exibidos no gráfico de prazo mais longo.


Espero que o que eu escrevi faça sentido! Obrigado.


Não há nenhuma razão especial para o período 288 além de um dia completo no gráfico M5. Também está dentro dos limites de onde os cálculos irão funcionar. Cerca de 20 a 1000 intervalos é o ideal.


Isso é uma coisa fascinante. Existe alguma maneira de usar a planilha para ações?


Eu negocio ações mais do que forex.


Deve funcionar na escala curta, dia de negociação, por exemplo. Você provavelmente precisaria fazer um dimensionamento dos dados na planilha, dependendo dos intervalos de preços.


"Em vez de negociar um lote, considere negociar em um décimo de um lote de unidades ou menos. & # 8221;


Este é um princípio básico na arte de negociação.


Muitas pessoas que são subcapitalizadas trocam um lote inteiro ou contratos futuros.


Embora a negociação de unidades mais flexíveis não signifique que você vai ganhar, essa é outra história.


Qual fórmula você usa para a estimativa de parâmetros de tendência da amostra de dados?


Qual parte você está se referindo exatamente?


A fórmula para estimar qualquer tendenciosidade é baseada em uma medida de volatilidade para cima / para baixo. Nos exemplos acima (curvas máximas), um mercado simples & # 8221; modelo foi utilizado. Isso não significa que não significa apenas que não há nenhuma suposição anterior sobre a direção da tendência.


Steve, muito obrigado por este artigo. Como por wikipedia (en. wikipedia / wiki / Random_walk), a segunda parte do fatorial deve ser n-m, não m + n. Isso é um erro de digitação, ou eu sinto falta de alguma coisa? Obrigado.


A fórmula I mostrada na caixa acima é que para encontrar a probabilidade de um ponto máximo ser alcançado em uma caminhada aleatória & # 8211; Qualquer ponto é igual ou inferior ao máximo. Eu verifiquei isso agora com a versão da Wikipedia e, de fato, a menos que n (o tempo que você está olhando para frente) é muito pequena, as duas fórmulas (n + m) ou (n-m) dão resultados idênticos. Isto é devido à simetria da função combinatória. Mas o caminho certo de acordo com o princípio da reflexão é (n + m). Há também o caso especial para usar (n + m + 1) onde a paridade é diferente em m e n. E por causa da simetria (m + n + 1) é idêntico a (n-m). Novamente, a menos que n seja muito pequeno, isso não fará muita diferença para os números se você usar (n + m) ou (n-m).


Muito obrigado pela explicação. Você poderia também gentilmente explicar como m está relacionado com os 62 pips?


Como eu entendo:


n = número total de etapas.


m = o número de etapas necessárias para tocar em +62 pips.


Na fórmula, sabemos qual é a probabilidade de o máximo ocorrer após m passos, mas como isso está relacionado com +62 pips. Como sabemos que isso é 62 pips e não mais / menos? Obrigado.


O movimento de pip depende do fator de escala no processo aleatório. Essa escala é governada por duas coisas:


O período de tempo para cada passo & # 8211; por ex. se for 5 minutos, 15 minutos, 1 hora ou o que for.


E, em segundo lugar, a volatilidade porque isso lhe dirá o movimento esperado no processo aleatório para um determinado período de tempo.


A partir disso, você pode calcular a distância esperada e converter em pips ou porcentagem.


Oi Steve você conhece a teoria financeira que tem uma conexão próxima com a ordem de stop loss? artigo muito bom.


A teoria subjacente é mais baseada sempre em modelos de probabilidade estocástica. Isso é usado para caracterizar a volatilidade e o risco dos preços. Na teoria básica, uma caracterização da volatilidade é encontrada e esta é então usada como forma de modelar o desenvolvimento do preço. Isso sendo em termos de uma distribuição de probabilidade que permite algum tipo de previsão antecipada. Mas há muitos outros que cobrem áreas mais obscuras.


Há também modelos de risco de distorção que tentam modelar eventos de cauda longa. Por exemplo, o processo de stop loss distorce os preços à medida que certos níveis são atingidos ou de eventos de alto impacto / baixa probabilidade que caem além dos modelos convencionais.


Gestão de risco financeiro e teoria VAR é um bom ponto de partida.


Talvez você esteja planejando a versão mt5 deste indicador? Eu já tenho a versão mt4, mas o mt4 é muito mais lento no backtesting.


Tenha um bom dia.


Eles disseram que o mt5 é mais rápido. Não posso dizer que tenha visto uma diferença ainda no meu backtesting, mas acho que depende do que você está fazendo.


Não há uma versão 5 no momento, talvez mais tarde, se houver mais demanda por ela.


Um artigo muito interessante.


Em 23 de fevereiro de 2015, você forneceu as equações para p (win), p (lose) & amp; p (aberto) em uma resposta para BYO2000. A maior parte faz sentido para mim, mas você pode explicar como chegou às equações para p (ganhar primeiro) e p (perder primeiro).


Certo. Esta é uma probabilidade condicional usando a teoria padrão.


Se o preço tocou tanto o stop loss como o take profit durante um período de tempo, então.


existem duas probabilidades distintas com esse conjunto: ou tocou no SL primeiro ou tocou no TP primeiro.


Durante o período. Daí os dois casos diferentes para contar para isso.


Great job, but I personally don’t trust that much the random walk theory. It states, that future princes are normally distributed and the probability to take each value depends on the standard deviation (volatility in this case.)


Based on that, how can big price fluctuations be explained ? For example, taking random walk as an absolute truth, it would be extremely bizarre to see prices fluctuations above 3ơ (3 times the volatility) since probability is less than 1% but if you look at the market it has happen quite a lot.


If you required the specific examples let me know I will show you.


I want to know your opinion about this, and if is possible, have an idea of how efficient is this strategy when you use it.


I completely get where you’re coming from. A lot of people – especially technical traders – don’t agree with the RWM. That’s their opinion. I am not going to spend a lot time defending it as there are people out there who can do a lot better job than I can. Though what I can say is that much of the criticism I’ve seen is unjustified or just plain wrong. What you say above only holds true if you assume that volatility and drift in the model never changes. Actually though these components are changing all the time.


Volatility measuring is by definition lagging so you can never know what the instantaneous volatility is. You can only estimate it based on information available at the time. So when you say a 3x volatility move, what that really means is 3x what the volatility was in the past. Not what it is at a given instant. This is a limitation of measurement not the model. As I mentioned in the article implied volatility can give you a forward measure and that can be used instead.


So far RWM is the best and simplest explanation of market moves I have yet seen. If something better comes along I’ll be the first to use it. I’ve seen advanced simulators and I can tell you that you can’t tell the difference between them and any other price chart – every type of chart pattern is seen and is reproducible. The word “random” just seems to be a red flag to a lot of people. But the RWM has both a deterministic and non-deterministic part and it’s the deterministic part we try to discover and trade on.


Hi can you explain how to upload new metatrader data in the excel spread sheet please? Thanks your help is appreciated.


I would be grateful if you could perhaps give a more detailed explanation as to how you calculated the “maximals” table (as used in your Excel Worksheet).


At first glance, it does seem to be related to some form of cumulative function of the “p(Yn=m)” probability you mention in the “Random Walk” explanation box – maybe some kind of cumulative distribution function, but it is not described here.


I read the related material and links provided about the “Random Walk”, as well as other sources of information by different authors, but can’t seem to find anything that would explain how you calculated the “maximals” table.


The maximals are a forecast of how far the price is expected to move (maximal distance) over a certain time. That’s taken from the random walk model with or without a drift component. The drift gives the trend so that allows the model to forecast changes in different directions (other than a flat market). There are standard mathematical procedures for working this out and creating a discrete time-based probability distribution from it. From that distribution it’s possible to work out the probability of a price move within a certain time interval.


There’s some more discussion about it here. Duke uni also has a lot of good info on this subject. The above papers are giving an overview.


There’s something I don’t understand. Your chances of winning are higher (let’s say 68.3% to cite your example), but the amount you would win is lower (26.9) than the amount you lose (-67.3).


This leads to a negative expected return:


So, if you run this strategy many times you’ll end up losing money, right?


You also have to account for the probability of the trade still being open. There’s an 8% probability that the price doesn’t reach either the stop or take profit and that accounts for the missing value in the expectation. So the value (1-0.683) in your formula doesn’t account for all other outcomes which have to be integrated over to find the true expectation. There’s always a finite probability that the trade will be open however long you wait. If you look at figure 5 for example the p(open) graph gets smaller but it never quite becomes zero. In either case this is a truth of computation – it’s not something that applies just to this strategy.


Indeed, the expected profitability of a trade if I am not mistaken should be an integral of an asymmetric capped maximal curve. Have you per chance made this computation in your testing, as I think this is the most relevant quantity to optimize on?


Another thing is that this is still very simplistic in the sense that the construction of your stop loss and take profit are based on how you built your signal. My understanding is that the signal you built is a simplistic version of something along this line: if you feel that the market is overselling an asset (downward trend) you will buy (hence the trend+ and trend - that were not very intuitive on the first reading). Then wanting to build your asymmetric maximal curve makes sense since you look at an asymmetric volatility which kind of tell you if the trend was fundamentally stopping and the future was noise, I can still expect the market to trend lower by x pips due to underlying volatility. I am not sure the way you measure it though makes sense given that in fact, what you want to look at is the volatility of the price if there were no trend going on, which will give you limit that will be breached quickly if the trend was to continue and the prediction was wrong. I feel this is in a sense a better way to include the potential signal into your stop loss, as the stop loss should then be tighter but on a justifiable note.


Overall I quite like the ideas you expose here, but I feel the main point which is the expected return computed from the integration of maximal curve is missing, as this is what is verifiable in live trading or backtest.


The more interesting question to me is the reverse hypothesis. That being the maximum likelihood estimator (MLE) of the trend and volatility given a noisy sequence of prices. Because without knowing this any expected return would in any case be zero when you cannot make any prior assumption on trend direction (the deterministic) and you have a symmetric range of probabilities. Solutions to the MLE can be found but that does mean using Monte Carlo simulation or something similar since there are no closed forms to this problem. This is something we are working on.


Does that indicator work on anything for e. g. on CFD or just forex?


It should work on most instruments including CFDs: Metals, Oil and so on. If you have any problems just raise a support request.


i think if you use rrr like this, this %82 tp probability also cant do any help for our accounts,


but may be this is what us new traders want to hear, wide stop loss and tight take profit, it is alluring for newbies.


özkan (izmir/ Turkiye)


Nobody here is recommending an sl or any other value.


The article is an analysis of the stop loss placement and what result that is having on your rr and on probability winning or losing the trade.


If you had read further than para one you would understand your remark has no logic but is the view of the amateur.


Great article-thanks very much. Is the spreadsheet still active so that historical data can be copied, or has it been protected since the last posts? I have Excel 2010 but there is no apparent way to paste data in the Input tab.


Yes it is still active. No, it’s not locked. But to edit you will need to save a local copy. This is because Excel 2010 and later will disable edits for any spreadsheets downloaded from the web. If you are still having an issue with this please use the contact form to get in touch and I’ll take a look.


Thanks, the problem seemed to be with Excel 2010. I tried 2013 and it works fine.


Hi, I was wondering how the maximal curves are built using estimated volatility. given 5m volatility of 10pips, so volatility for 24hr = s5*sqrt(24*60/12)=0.01697pips. Then for P(X>=TP) we can use z = (x-mu)/s24 and Pr(z>=(TP-mu)/s24), for TP=40pips and mu=0, im not getting 82%probability but 100%. I’m not sure this is the right way to do it. Wondering if you could point me to how to build those curves?


Please see reply below.


Hi, nice article I’m trying to understand it. I have a question about how sample volatility is used in the calculation of maximal curves.


Am i supposed to approximate the binomial dist with std normal using z=(x-mu)/s = x/s if mu=0, s=0.001 then calculate P(z>c) where c is TP. So if s5=0.0010 per 5m, we get 24hr volatility as s24=s5*sqrt(24*60/5)=0.01697, if target price is 40pips then is P(x>=.0040) or using z, P(z>=0.0040/s24) but this doesn’t give me 82% chance of reaching TP?


Further, doing this only gives me the prob of z being above c at the “end” of the holding period. but that’s not what we want, we want to find P(z>c) at any intermediate time? Would be great if you could explain.


It is a cumulative probability of maximal distance traversed in a certain time. So by that definition it covers all intermediate times between such as P(z>c) in your notation. I would also calculate the 24 hour volatility directly if that is what you need, rather than trying to scale up from 5M timeframes.


Excuse me Steve,


is this spreadsheet valid only for the EURUSD pair? I tried to use it with AUDUSD values but got thousands pips large TP and SL… While with EURUSD values it works perfectly.


Yes it is compatible with AUD/USD. This problem is most likely due mixed data histories. Please ensure all of the old data is removed and reset the “pip value” selector.


Alternative you can use the 4 indicator which is now available and does this for you:


This is a very detailed article and confirm to me what I thought when I approached the Forex market after a short period of trading. You mentioned at the end of the article that you have also an EA that make the same calculations of the TP/SL as your great Excel spreadsheet and I would be very happy to integrate it in my own EA used to trade.


Is it available for download free? Does it work on “live” data taken directly from 4 without the need to export them?


Thank you very much for your answer and for your website!


Yes it can work with a live price feed. It could be made available as an indicator in the future – but that would depend on the interest as it would need to be recoded.


is this spreadsheet valid only for the Pounds pair?


It should work with any pair. If you’re importing data from Metatrader please make sure the sizing is correctly set in the data tab.


Hi, I can`t paste right, I mean when I copy historical data from 4, and paste it to input as you said, there are no spaces between the comma, and it is not divided as on your picture. In your picture each cell gives one information like date, etc, but when I paste it the information starts in one cell and ends in another. I have new excel, what should I do?


If your data is all in one column as it sounds then you need to use the “text to column” function in Excel to format it into separate cells. If you saved it and opened it as a csv file it would normally do this for you.


One of the best articles I’ve found on stop and profit targets. Thanks for sharing your knowledge with a newbie like me!


problem with excel file can you upload it again?


You will need Excel 2010 or later otherwise some of the features will not work.


Hi, I can`t paste the same as you when I use data from 4. The numbers f. ex. start in one cell and end in the other. I have new excel. O que devo fazer?


That’s a very nice of you Mr. Steve. According to calculating volatility and RRR, I am wondering that as a day trader with a very short horizon period of investment. Ex. 5-15 Mins chart. This method could be potentially help any trades? Why I said so? What being said is that If I my trade set up were 2/1 RRR, which I have to set my SL at -200% and TP at +100%. In the long run, do you think this kind of statistic will help the trades to win? Literally, taking a smaller pips and widening a SL could really boost up a winning percentage which means that once I losses such any single trades I have to try to double up profitability to cover such losses. Here come to my question, in this kind of situation that I earlier mentioned, do you have any way to fix it? or if the theory you mentioned works, how could you adapt to use with scalping trader and day trader style?. Thank you very much for your consideration in advance.


It’s a good point and one I should have expanded on in the article. In my opinion it doesn’t make a lot of sense to have a fixed ratio of SL to TP for all cases. The choice should be dynamic because it depends entirely on the situation you are trading and the market conditions.


A breakout trade for example may have a low probability of success but a high payoff. As well it is usually clear after a short time whether the breakout is going to happen or not. In that case it doesn’t make much sense to allow say a 2:1 SL/TP which would allow a big drawdown. When in fact if the draw happens you already know the setup has failed. In other situations the reverse may be true.


Ótimo artigo. Can you explain why you calculate volatility on open/close data? “From the open/close data, I calculate that to be just over 10 pips per 5-minute period.” Why don’t you use the ATR or high/low data? I’m trading daily charts, so the difference is quite large.


You can use ATR. You can also use the Bollinger bandwidth as a vol measure. Whichever you use you should get roughly the same ratio of TP/SL however because the measures are relative to each other and not absolute. If you need to calculate a specific probability then in this case some calibration is needed depending on which vol metric is being used.


thank you for your good strategy . i have question : i tried to calculate probability for volatility of 10 pip per 5 min.


for 1 hour for distance 51. which gave us n=12 and m=6 for box formula. but i calculate 5% for probability and from your curves it seems true percentage is 15% can you tell me why my result are different ?


Your value seems too low. Because these are probability functions the curves need to be worked out as a cumulative value of the function (not the point value) over the move distance you are looking at.


Probably the best forex article I ever read.


Hi, very nice and useful article. I was wondering if it was possible to have a numerical example of how to calculate the probability using random walk. In your example, are you assuming a drift component=1? Or less?


Agradeço antecipadamente. Tchau.


“You can have the price rising then falling in which case it passes a TP AND SL. Por exemplo If you have very close TP/SL then these have near 100% chances of being hit.” If you imagine a space of outcomes you have.


P(Neither TP nor SL hit)”


EURNZD, EURAUD, EURGBP, EURCAD whipsaw upwards before collapsing. The greatest one was the EURGBP this time round.


(One either widens their SLs 150-200pips for crosses or tightened stops risked a larger loss when it hits the SL. Other than staying out completely.


Prior to ECB, EURCAD went to low of 1.36945. The whipsaw touched SL of 1.3765 before retracing downwards. For a short position, adding a Stop Loss gave away profit of 70 pips. Does assigning probability described applies to risk events like ECB?


(The EURGBP is now back at the same level, though it whipsawed the most. )


What’s your view about contrarian trades (that agrees with TA at the time you look at it)? example would you have longed the EURNZD on Mar 5, would using this probability analysis tell one not to long but short it instead although the charts are long – Measuring the strength/continuity of reversal moves.


-Does assigning probability described applies to risk events like ECB?


Not unless these events occur frequently within the time sample you are looking at, but even then its unlikely you could ever model them to predict an outcome. Major news releases – those with very high impact – are by their nature unpredictable and can/will change the trajectory of the price in ways that are beyond normal statistically analysis.


-What’s your view about contrarian trades (that agrees with TA at the time you look at it)? example would you have longed the EURNZD.


Absolutely, contrarian trades can and do work – but then there are limits, I would be cautious about trading contrarian against strong fundamentals. For eg, I wouldn’t long EURNZD – simply because of the swap yield of -4.24% on the long side. The strong downward trend for the last six years is a reflection of that. But then if you’re scalping a few pips here and there it can make sense, and sure the Euro is going to turn sooner or later.


The maximal curves show the probability of how many pips price will move in /either/ direction right? I don’t quite get how the curves can be applied to just TP. por exemplo. if we want to know the probability of TP of +40 pips in 24hrs, yes the curves do give a probability of 82%, but wouldn’t it be 40 pips in either direction? ie. 41% of +40 pips & 41% of -40 pips? (because I’m assuming the curves have no drift, a walk in either direction is equally likely, etc.) Maybe I’m missing something – apologies if it’s a dumb question. Obrigado!


No only in one direction. The maximal curve will give the probability of a maximum point being reached, or equally if you apply the formula on the other side, to a minimal point being reached. When symmetric as you say, it is just mirrored.


So for eg: P(Z>+40 pips) gives an independent probability only of the price moving above the +40 pips level. It says nothing about the price falling say 200 pips below, this is why there is a separate case for the SL point.


With no drift, yes it would be the same (41% for a move either side).


(apologies again, I’m a bit slow) let’s see if I got this. The SL is a separate case.


So just considering the TP, what the maximal curve shows is P(Z>+40pips) + P(Z+40pips) = 41% ?


Not quite. What the maximal curve basically shows is the probability of a high-watermark being reached – and that applies for a certain time period only. So say you want to know the probability of the price going +40 pips or higher within 24 hours. That’s P(Z>+40 pips) from the 24-hour curve & it’s 82%. After 1 hour, its 28% (thereabouts, I am just looking at chart not in Excel.)


Thanks for your patience Steve 🙂


It was probably my fault, but my previous comment was strangely truncated. What I wrote was to ask if the maximal curves show: P(Z>+40pips) + P(Z+40pips)=82%. If so, doesn’t that also imply P(Z<-40pips)=82%, which surely cannot be? I'm lost here.


Você é bem vindo.


I have to answer here because its not possible to add a reply any deeper (it will be better to continue this in Forum section where there is more room.):


–What I wrote was to ask if the maximal curves show: P(Z>+40pips) + –P(Z+40pips)=82%.


There is no addition here (did you mean P[Z 40pips, it gives this as 82% from the curve. This tells me only one thing in isolation: that the TP has 82% chance of being struck.


Very cool idea & great article! I have some questions. In Step 3, can you explain how you got the table for p(win), p(loss), p(open)? Obrigado!


Certo. It’s standard probability theory:


Say p(wl) = P(price hits SL & TP)


P(wl) = p(TP hit) x p(SL hit)


p(win first) = p(TP hit) x p(wl) / ( p(TP hit) + p(SL hit) )


p(lose first) = p(SL hit) x p(wl) / ( p(TP hit) + p(SL hit) )


p(win)=p(TP hit) – p(lose first)


p(lose)=p(SL hit) – p(win first)


Thanks Steve. I love your articles.


Could you commend on reversal moves? Trades such as EURAUD on 20 Feb hit a low of 1.4385 and spiked upwards to 1.4583.


100-200 pips reversed moves can be pretty tough psychologically to place stops – where you don’t want them too close, yet when it hits SL it erased off those hard earned gains or puts one in steeper losses.


I was in some other trades that reversed off its lows. As I read your posts, I know we are going down to really precise levels now. That -100+ stoploss can take place in a very short span of time and hurt quite a bit if one’s position is in several trades at the same time.


EUR/AUD is quite a volatile pair, with about 50% higher volatility than EUR/USD at the moment.


That is for a 1 day trade, for the short side I would use a ratio somewhere around TP=56/SL=250. Are you trading the long or short side because it really makes a difference here. On the buy side there’s very high swap rate (-3.13%) to take into consideration.


Reversal moves are all part of the normal daily volatility in the markets. I’m of the view that it’s better to have a lower leverage so that these events can be withstood – because in the scheme of things a 100-200 pip move is pretty insignificant really.


Obrigado. I was thinking through my mistakes, and reading your spreadsheets. Essentially the trades I got stopped out was GBPUSD, GBPCAD, EURCAD. It is trade timing.


SL=250 is tough psychologically (I am not going to be able to test 200 plus pips.)


Actually some profit from the EURAUD, EURNZD. I trade several illuid pairs gbpnzd and also trade short side for some pairs, and hedge sometimes as well.


I will look through the win loss ratios, and trades probabilities to examine the trades and see if I can improve on where it went wrong. You have got a great resource. I was already doing breakouts, grid trading, carry trades for some time, but I still come back because everything was very well written and learn from someone who is strong.


Could you write an article on basket trading? I have been practicing, don’t know if this is something doable on a live account.


nice idea! thanks steve, i will try this out and see how it works.


Hercules. Finance.


What does the “Invalid S/L or T/P” error message mean on 4/5?


The “Invalid S/L or T/P” error message appears if the stop loss or take profit you’re trying to place is not within the correct parameters of the limit and stop levels for that particular instrument.


Most of the cases, you just need to switch the price of Stop Loss and Take Profit, and the order can be placed.


For example, if you want to place a buy(long) order, then the Take Profit price should be above the price and the Stop Loss price should be below the price. And vise versa.


will also show you with error message immediately when you set wrong parameters of the order. If the concept is too complicated, you can also just order a position without S/L and T/P, then set these parameters by dragging the line in the price chart.


Ferramenta Forex AUTO SL e TP.


Forex AUTO SL e dispositivo TP.


Os dispositivos de perda e perda de lucro Forex AUTO param automaticamente e de acordo com as suas preferências.


Copie e cole o arquivo do produto & # 8211; AUTO_SL_TP_Device. ex4 - para abrir a pasta Experts anterior. Recarregue a plataforma 4.Confira as configurações de negociação ao vivo. Vá para Ferramentas & # 8211; Opções no menu principal de 4.


Encontre Expert Advisors na lista e defina as configurações.


Dê uma olhada no painel Navigator à esquerda da janela principal.


78 & # 32; пользователей находятся здесь.


МОДЕРАТОРЫ.


wrayjustin Troca de Moedas por Dólares FXMarketMaker Comerciante Profissional Hot_Biscuits_ Modelos e Garrafas spicy_pasta RichJG Astrólogo Financeiro El_Huachinango MOD finance_student Prop Negociante о команде модераторов & raquo;


Bem vindo ao Reddit,


a primeira página da internet.


e inscreva-se em uma das milhares de comunidades.


отправлено & # 32; 2 года назад автор A1nerd.


Quer adicionar à discussão?


[-] [eliminado] & # 32; 18 очков 19 очков 20 очков & # 32; 2 anos atrás (1 dia atrás)


[-] thetrebel GetRichorDieTrying & # 32; 0 очков 1 очко 2 очка & # 32; 2 dias atrás (0 dias atrás)


приложенияи инструменты Reddit para iPhone Reddit para Android móvel кнопки site.


Использование данного сайта означает, что вы принимаете & # 32; пользовательского соглашения & # 32; и & # 32; Политика конфиденциальности. &cópia de; 2018 reddit инкорпорейтед. Все права защищены.


REDDIT e o logotipo ALIEN são marcas registradas da reddit inc.


& pi; Rendered by PID 110036 on app-111 at 2018-04-19 10:09:08.914724+00:00 running f9d5fbf country code: UA.


78 & # 32; пользователей находятся здесь.


МОДЕРАТОРЫ.


wrayjustin Troca de Moedas por Dólares FXMarketMaker Comerciante Profissional Hot_Biscuits_ Modelos e Garrafas spicy_pasta RichJG Astrólogo Financeiro El_Huachinango MOD finance_student Prop Negociante о команде модераторов & raquo;


Bem vindo ao Reddit,


a primeira página da internet.


e inscreva-se em uma das milhares de comunidades.


Quer adicionar à discussão?


[-] Radeh Commodity Trader & # 32; 1 очко 2 очка 3 очка & # 32; 2 dias atrás (2 dias atrás)


[-] Radeh Commodity Trader & # 32; 1 очко 2 очка 3 очка & # 32; 2 dias atrás (0 dias atrás)


приложенияи инструменты Reddit para iPhone Reddit para Android móvel кнопки site.


Использование данного сайта означает, что вы принимаете & # 32; пользовательского соглашения & # 32; и & # 32; Политика конфиденциальности. &cópia de; 2018 reddit инкорпорейтед. Все права защищены.


REDDIT e o logotipo ALIEN são marcas registradas da reddit inc.


& pi; Rendered by PID 27374 on app-657 at 2018-04-19 10:09:09.117885+00:00 running f9d5fbf country code: UA.


How to Place Stop Losses and Take Profits Using a Maximal Strategy.


When entering a trade, how do you choose the point of the stop loss and take profit? Clearly, this decision will have an impact on how profitable your trades are. However, did you know that the placement of youdr exit levels can actually have more of a bearing on your profitability than the decision on which direction to trade?


In the volatile forex market, it is actually true. Given how important this decision is, it is surprising how little thought many traders give to this component of their trade.


In this article, I want to explain a quantitative strategy that will help you select stops and take profit levels for maximum profit. I also want to debunk some of the common misunderstanding around risk-reward setups, and show how following poor advice can ruin a potentially good trading system.


If you just want to try the stop loss/take profit calculator, and are not interested in the theory, please click here.


Why Guessing Stop Losses and Take Profits is a Plan for Failure.


A trading position will normally exit at one of two points. After entering the trade, either:


The price reaches the take profit ( TP ), and the trade finishes in profit The price reaches the stop loss ( SL ), and the trade winds up with a loss.


When deciding trade exits, it is sometimes tempting to make an educated guess. Some traders use technical features such as chart candles, trends, resistances and supports. Others simply choose a fixed ratio of profit target to stop loss.


While this is very common, there are several drawbacks:


It is error prone. When you guess the exit levels for a trade it is very easy to either overestimate or underestimate price movements. It is not repeatable and that makes it very difficult to analyze or improve performance. When there is no logic or methodology behind placements of exit points, you never know if a failure was due to a miscalculated TP/SL combination or because your strategy is not working. Traders will often move stops up or down on subsequent trades based on trial and error trying to find a “sweet spot”. It is very difficult to automate methods that rely on gut instinct or other subjective decisions.


There is nothing wrong with using technical analysis as a guide for timing the trade entry, nor for judging how far the price might move. Rather, the method I describe below is used alongside both charting and fundamental analysis.


The Fallacy of Using SL/TP as Proxy Risk-Reward.


Forex trading forums are full of well meaning, yet rather misguided advice about risk-reward setups and how to set your stop losses. Unfortunately, many of these people fail to understand the true meaning of risk or reward.


The idea that simply setting your stop loss smaller than your take profits will achieve a certain risk reward is complete nonsense.


Using risk/reward to set your trade entry and exits does not make any sense unless you know the probability of outcomes in a given trade.


Tome este exemplo simples. Suppose there is a lottery costing $1 to enter. The prize is $1m. By the definition of the naïve trader, this gives:


Reward/Risk ratio: 1,000,000.


By that definition, this would seem a fantastic game to play. However, suppose we know that two million people enter the lottery. This makes the odds of winning 1:2,000,000 (one in two million). Now we know the odds, we can calculate the true risk reward:


In other words, for every $1 you put into this lottery, you’d expect to get 50 cents back. Most would now agree this is not a very good game. Even though on the naïve trader’s reckoning, it had a reward to risk ratio of one million.


This example highlights the fallacy of using stops and take profits as a measure of your risk/reward.


In a trade, we have the real risk/reward defined by:


E (win) is the expected payoff in the trade, namely your take profit amount. E (lose) is your stop loss amount.


The Risk-Reward Relationship.


The first thing to realize about setting trade exit points is that the amount of profit you want to make on a trade is directly proportional to the risk you will need to take to capture that profit.


This is not a supposition, but rather a mathematical fact.


Take the following trading scenario. Say for example that a trader sees an upward trend on the hourly chart for USD/JPY (see chart below). The trend has been in place for around one day, so the trader thinks there is a good opportunity for profit.


He decides on the following setup:


Now let’s analyze this trade setup in more detail. The first thing to notice is the trader wants to capture a profit of 70 pips on the trade.


So what is wrong with this setup?


Based on recent price data for this currency pair, we can calculate that USD/JPY has an hourly volatility of 26.4 pips. That means, on average, the movement of the price over one hour is 26.4 pips. Sometimes more, sometimes less but this is the average.


This means the trader is trying to profit by 70 pips. In reality, he is actually betting against the market because he is relying on the fact that the price will not descend more than 20 pips from the open price during the life of the trade. That could be up to 30 hours if the current trend continues (from Figure 1).


Stop Loss Advisor.


Chart Indicator.


Choosing the right stop loss placement is a critical decision but it's often left to chance. This Metatrader tool advises where to place stops and take profits on any order. Just set the desired trade time and win ratio and the indicator does the rest.


Given the hourly volatility in USD/JPY is currently over 26 pips, this much stability in price would be highly unlikely. While the trade has a very low maximum loss (20 pips), which might seem like a plus, the chances of it finishing in profit are extremely low.


If we know on average that the price of USD/JPY moves up or down by 26.4 pips every hour, why would it do anything different for this particular trade? The answer is that it would not and the trade would probably strike the stop loss for that reason.


Due to the volatility in FX, this is true even if the predicted trend continues.


The basic problem with the setup was that trader was trying to capture too much profit without accounting for volatility.


Remember that in forex, volatility is not something you can avoid by careful trade picking or a clever strategy. It is an absolute certainty.


That’s why it is far better to make volatility work for you rather than against you.


The question then is when setting up a trade, how do you know where to place the exit points other than just taking a wild guess? The following will explain how to do this.


Calculating Stop Losses and Take Profits Using Maximals.


The method I prefer to use is based on a technue known as maximals . What this does is give a precise formula to work out the probability of the price moving a certain distance from the open during a given time.


This model gives a complete distribution of price moves for a given volatility. This method works for any timeframe, minutes hours or even months. It also works equally well with either historical (past) or implied (future) volatility.


In deciding trade exit points, there are three things to consider:


The expected timeframe of the trade (related to profit target) The market trending behavior The profit target.


Let’s take a look at each of these.


Step 1: The Time Frame.


The type of trader you are will have a bearing on the time that your trades need to stay open to reach your profit target.


A day trader or a scalper would hold a position for hours, minutes or even seconds. At the other extreme, a carry trader holds positions for weeks, or months. For the carry trader, capital gain on the trade is usually less important. The goal is to hold the position open for as long as possible to accumulate interest.


Clearly then, profit and time are linked. So in setting your trade exit points, the first step is know precisely how far the price is likely to move in a given timeframe. Once you know this, you will be able to decide a realistic profit target.


Tome o seguinte exemplo. Figure 2 below shows EUR/USD over five minute intervals (M5). The chart spans a 24-hour period.


The first thing I do is calculate the volatility over my chosen period. From the open/close data, I calculate that to be just over 10 pips per 5-minute period.


Once I know how volatile the market is, I can project the price forwards to work out the probability of a certain move x hours (defined by 5-minute intervals) into the future.


To do this, I need to calculate what are known as maximal curves (see box for an explanation). Briefly, taking the volatility as input these curves will tell me the probability of a maximum price (either up or down) being reached.


Figure 3 below shows the maximal curves calculated for 1 hour to 24 hours ahead for the EUR/USD chart.


For example, looking at the maximal curve for 24 hours (top line), I know the price has a 76.8% probability of moving 62 pips within a 24-hour period. Whereas it has a 40% probability of moving more than 141 pips in that same time frame.


The Random Walk.


I only give a brief description here of what are rather complex calculations. The best market model we have for forex is the random step process or random walk.


This just means that in every interval, the market moves by a random step value. The price can slant towards an uptrend or a downtrend with a drift parameter.


In essence, the longer the time interval and the greater the volatility, the further the price can move from the existing level.


From these we can calculate the probability of a price change over any length of time.


Hedge funds and professional traders often use maximal curves or some variant thereof. The reason they are so important is that they allow you to setup your trade accurately in terms of time and profit capture. The curve tells you if the amount of profit you want to make is reasonable in terms of the time span.


For example, I know if I wanted to capture a 300-pip movement, I would likely be waiting roughly ten-days based on the current volatility level. This is because from the curve, there is only a 10% chance of the price moving 300 pips in any 24-hour period.


Step 2: The Market.


If the market is flat, or trending in a certain direction this will have a strong bearing on where you place your stops and profits. In terms of the model, it means that we have an asymmetric distribution of price movements.


There are several ways to allow for this, but the simplest and the one I prefer is to use a different volatility for the upside and downside price model.


The statistical skew is useful here because it tells you how asymmetric the volatility distribution is and allows you to add an upwards/downwards drift.


Random walk – not trending.


Trend up – positive drift.


Trend down – negative drift.


With the random walk, up and down price moves are equally likely. When trending, two different sets of maximal curves are needed, one for up moves and another for down.


Step 3: The Profit Target.


Having decided on a timeframe and on the trending characteristics, I can now choose an appropriate profit target that will give my trade a high win probability.


Say I’ve checked the chart, and decided to buy at the current market level, and I decide my target will be +40 pips and my cut off will be -100 pips.


The table below gives the probability of my exit points being reached in each of the three market conditions.


Trend +: Trend in same direction.


Tendência & # 8211; : Trend reverses direction.


Flat : Sideways market.


My trade setup is then:


Take profit +40 pips 82% probability of reaching TP within 24 hours.


Stop loss -100 pips 57% probability of reaching SL within 24 hours.


What this analysis tells me is that EUR/USD has a certain chance of reaching the TP/SL levels within my trade timeframe. But it doesn’t tell me which is reached first.


What I would also like to see is the probability of the trade actually making a profit or loss. The price could reach the stop first, and then the take profit. In that case, my trade would finish with a loss. It could alternatively reach the take profit first, in which case it wins. Alternatively, it may neither reach the stop nor take profit level in which case the trade remains open.


Based on this analysis I can use standard probability theory to work out each outcome for the trade:


My best outcome happens if the short-term trend reverses, that is if the market rises and makes my buy profitable. The worst outcome happens if the trend continues in the same direction ( trend+ ). In that case, I have a 42% chance of the trade ending in profit, and a 47% chance of it ending in a loss.


When I set the trade up what I am looking for is the chance of the take profit being reached, to be at least 1.5x the chance of the stop being reached. This will give a win ratio of around 70% or higher.


Also, remember that if you move the stop loss or take profit while the trade is open that gives you an entirely different set of outcomes.


Analisando o comércio.


To see how the stop and take profit levels shift for different trading timeframes, I can work out an envelope, which will give me a fixed win ratio. The graph below in Figure 4 shows this plotted out for my example trade.


From this, I can see that if I were trading over a 12-hour period, I could choose to set:


That would achieve the same win ratio. It would also give a lower profit of just +26.9 pips.


With my 24-hour timeframe, I can also see how the possible outcomes will change over time.


The chart below (Figure 5) shows the probability of a win, a loss, or the trade remaining open over 24 hours – the expected lifetime of my trade.


From the chart, I can see it has the highest chance of closing in profit within the first 90 minutes of being opened. Thereafter, the chance of a loss rises significantly.


This is because the maximal curves become flatter for longer periods. If you check Figure 3 again, you will see that the curves for 24-hours and 18 hours are quite similar, whereas there is a big difference between the 1 hour and 6-hour curves. The highest differential is in the first few intervals where the curves are steepest.


Finally, given the above data the forward expectancy can then be calculated to find the expected return from the buy and the sell side.


Gerenciamento de dinheiro.


As shown above, your stop distances have to work in terms of your profit target and the volatility levels.


New traders often place stop losses too tight, thinking they are reducing risk. The usual reason for this is that they are using far too much leverage and try to reduce exposure by placing limits on individual trades. It is better to manage risk through trade size (exposure) than to use stop losses which don’t make sense.


Suppose you see a trading opportunity, and the potential drawdown needs to be 300 pips to capture that profit. If 300 pips is not an acceptable loss, then it is better to reduce leverage and adjust your trade size downwards to give you more flexibility.


Instead of trading one lot, consider trading in one tenth of a lot units or lower.


What is most important is that a potential loss (or drawdown amount) on a trade should be manageable within your account. This should be part of an overall money management strategy so that you know your loss limits and those losses, even in succession will not cause a margin call or bankrupt your account.


Remember, over-leverage is the #1 killer of new forex traders .


Stop Loss Calculator.


I provide the Excel spreadsheet with all calculations here so that you can download it and try this system out for yourself.


For instructions on how to use the sheet, please see here. The spreadsheet does not have the live price feed which the 4 indicator uses, but you can manually paste in historical price data from to work out optimum take profit and stop losses in the same way I’ve explained.


The indicator, which does the same calculations in real time and includes additional features is also available. Veja abaixo para mais detalhes.


Gostaria de se manter informado?


Negociar sem parar perdas pode soar como a coisa mais arriscada que existe. Um pouco como ir montanhismo. Como aproveitar ao máximo os tipos de pedidos de Forex.


Ordens são muitas vezes vistas como nada mais do que um show paralelo ao negócio real da negociação. Ainda o intervalo. Value at Risk: How to Calculate Forex Risk.


To manage this risk, what some do is make a simple guess to estimate the potential loss involved. The. Por que a maioria das estratégias de linha de tendência falha?


As tendências são todas sobre o timing. Tempo-los bem, você pode potencialmente capturar um movimento forte no mercado. Day Breakouts Volume de Negociação.


Essa estratégia funciona detectando breakouts no EURUSD nos momentos em que o volume está aumentando acentuadamente. Geralmente. O Engulfing Candlestick Trade & # 8211; Quão confiável é isso?


Você pode ter visto que há inúmeros artigos na web declarando engolfando estratégias são uma certeza. Estratégia de fuga do canal Keltner.


A maneira clássica de trocar o canal Keltner é entrar no mercado à medida que o preço quebra acima ou abaixo.


Thanks for this awesome approach of this whole sl/tp theory. After using the r/2r (simply putting your stop loss on half the distance of your tp) approach for a while I already concluded that this only works if you pick the right direction, making this only useful for somewhat predictable stocks. In forex however I already came to the conclusion that the distance to the entrypoint matters more than the direction (since forex seems a bit more unpredictable). I first thought the chance of my trade hitting a double x distance increases exponentially but this made me take a lot of small profits (which is still profit, but not very efficient). Your approach is very logical and you show the numbers that just make sense. Obrigado. One question remains though and you seem to be the right guy to ask this: how do you determine the trend of a forex couple? You watch a long term trend, a day trend or an hourly trend do you use a calculable relation to the expected time you need to hit your exits?


I have hard time to reproduce your results.


I try to calculate the lowest curve -1HRS in Fig3.


I use your data from Fig2 – time step-5min with volatility 10 pips.


According to the the equation in the box :


for distance 0 pips I receive - P(Y12=0)=((FACT(12)/((2^12)*FACT(6)*FACT(6)))*100=22.56%


for distance m=2 (20pips) I receive - P(Y12=2)=(FACT(12)/((2^12)*FACT(7)*FACT(5)))*100=19.34%


I am not sure exactly which results you are referring to. To get to the end result there’s a chain of probabilities that have to be calculated through each time slice.


The examples shown were done for EURUSD, with a particular set of parameters at that time.


Thank you for the interesting paper.


Can you share how do you calculate upside and downside volatilities?


Does Your Stop Loss/Take Profit indicator use the same statistical model of price distribution for probability calculations as the in Excel spreadsheet demo or a more complex one?


No they are different, please see the earlier replies on the same.


Thank you so much for your stoploss/take profit info. I am using an android phone and has also downloaded the sl/tp calculator, but cannot find the features i need from my android metatader. How can i do it?


thank you for your articles, this particularly and the spreadsheet that is a great tool in my opinion.


I would only need a punctualization: in the sheet “Proc”, the cell “Current price” is only used to calculate the TP and SL levels, right? I tried to enter very different prices but nothing changes in the results of probability to win/loose, ecc., only the SL/TP levels are recalculated. My question is: now on EURUSD for example we are at the top limit of a strongly ascending channel; if I buy now, how can the win ratio to be the same in the same period of time as if I’d buy at the middle of the channel or at the lower limit?


Thank you for your kind reply.


The spreadsheet is only a simplified demo and doesn’t take any of the live data feeds that the indicator does.


thanks for this great post. I feel very confident about it.


I know that few years has passed since your writing, but I have a question: On ‘Proc’ sheet (D,34) you have a fixed constant of 0.85 – is there anything magical in it? Maybe my question is out of sense, and I’m truly sorry if it is.


This value isn’t used anywhere in the sheet.


Why I am getting lower “Set take profit at” than buy price? I am experimenting and set different currenct price values but not matter what – I am getting take profit which would not be really profit. Here is what I see:


I have my own system for using stop loss. I always use fibo ratios and never set any lower than the day pivot level. It works out most times.


Great post thank you.


Very reasonable and well suported thinking. But for what I understood wht woud be advisable in the specific example, would be to open the with that setting of SL/TP and close it with a loss or lock profits after 90 min to 1 hour, since after that time period, the increase of probability to hit the SL will augment dramatically. O que você acha?


Yes that’s exactly right the probability of either the stop or profit being hit could be much greater after a big move – these probabilities are changing every second. It would be a decision for the strategy being used as whether to move the stops or close as that point.


what if i want to have a unlimited take profit? for example i invest 300 on XRP and it hits 3000 usd. my profit is 2700 on the original investment of 300 so my max is 5700. is there a way of having a unlimited take profit if i want to keep letting my XRP grow? what if i want to have this grow until it reaches 1 million? will Etoro let me do that?


Hi Steve – Ótimo artigo! Could you please advise how the reward:risk is calculated. I am newbie and till now I was calculating reward:risk by just dividing TP pips/ SL pips, but learned that it is not right after reading your article. I am not able to get the mathematical figure shown in the excel sheet for the target win ratio I selected. Could you also please show with an example of how probability trade wins and probability trade losses are calculated. Muito obrigado.


I really like your article. I’m wondering, do you have a spreadsheet for calculating maximal curves? Like in Figure 3. I’ve downloaded the Stop Loss Calculator excel file, but this one is not there, or at least i cannot see it.


That graph is from a different spreadsheet. It may go in one of the online tools at some stage.


Hi Steve. I was looking for a solution for Stop Loss placement and came across your article. Thank you for what seems to be a great solution. I do not use 4, but have been able to export the historical dat. My only challenge is that I cannot paste the data in the provided columns, as the cells are protected. How do I get around this? i. e. Can I get the password?


A password isn’t needed. This happens when you are pasting in too many rows for the range. Just clip the rows to the max number allowed and it should be fine.


Hi Steve, hope you are doing well 🙂 Awesome indicators – I love how everything is mathematically explained and makes great sense! (I have a math/engineering background). Already purchased a few of the indicators and looking for my next one to buy 🙂


For this Stop Loss/Take Profit indicator, is there any reason that 288 periods were used for generating the outputs?


I find that most trends on the pairs I trade move in 20-30 period cycles, so I use that as the sampling period so I can for example bring up a 15 min chart and have an SLTP value that coincides (rather than use a longer period and have to consult the shorter timeframe for SLTP values). Is that too short a period?


What would be cool is if shorter timeframe SLTP values could be displayed on the longer timeframe chart.


Hope what I wrote makes sense! Obrigado.


There’s no special reason for the period 288 other than it’s one complete day in the M5 chart. It’s also within the limits of where the calculations will work. About 20 to 1000 intervals is the optimum.


This is fascinating stuff. Is there any way to use the spreadsheet for equities?


I trade equities more than forex.


It should work on the short scale, day trading for example. You would probably need to do some scaling of the data in the spreadsheet depending on the price ranges.


“Instead of trading one lot, consider trading in one tenth of a lot units or lower.”


This is a basic principle in the art of trading.


A lot of people that are undercapitalized trade one full lot or futures contracts.


Although, trading more flexible units does not mean you are going to win…that is another story.


What formula do You use for the estimation of trending parameters from the data sample?


Which part are you referring to exactly?


The formula to estimate any trending bias is based on a measure of upward/downward volatility. In the examples above (maximal curves) a “flat market” model was used. This doesn’t mean no trending it just means there’s no prior assumption about direction of the trend.


Steve, thank you very much for this article. As per wikipedia ( en. wikipedia/wiki/Random_walk ), the second part of the factorial should be n-m, not m+n. Is this a typo, or I do miss something? Obrigado.


The formula I’ve shown in the box above is that for finding the probability of a maximum point being reached in a random walk – that is any point at or below the maximum. I checked this just now with the Wikipedia version and in fact unless n (the time you are looking forward) is very small the two formulas (n+m) or (n-m) give identical results. This is because of the symmetry of the combinatorial function. But the right one according to the reflection principle is (n+m). There’s also the special case to use (n + m + 1) where the parity is different in m and n. And because of the symmetry (m+n+1) is identical to (n-m). Again unless n is very small this won’t make much difference to the numbers if you use either (n+m) or (n-m).


Thanks a lot for the explanation. Could you also kindly explain how m is related with the 62 pips?


As I understand it:


n = total number of steps.


m = the number of steps needed to touch +62 pips.


In the formula we know what is the probability that the max will happen after m steps, but how is this related with +62 pips. How do we know that this is 62 pips and no more / less ? Obrigado.


The pip movement depends on the scaling factor in the random process. That scaling is governed by two things:


The time period for each step – for e. g. if it’s 5 minutes, 15-minutes, 1 hour or whatever.


And secondly the volatility because that will tell you the expected movement in the random process for a given time step.


From that you can work out the expected distance and convert to pips or percent.


Hi Steve do you happen to know the financial theory that happens to have a close connection with the stop loss order? very nice article.


The underlying theory is most always based on stochastic probability models. This is used to characterize price volatility and risk. In the basic theory a characterization of volatility is found and this is then used as way to model the price development. That being in terms of a probability distribution that allows some kind of forward prediction. But there are plenty of others which cover more obscure areas.


There’s also distortion risk models which try to model long tail events. For example the process of stop losses distorting prices as certain levels are hit or of high-impact/low probability events that fall beyond conventional models.


Financial risk management and VAR theory is a good starting point.


Maybe you are planning mt5 version of this indicator? I already have mt4 version, but mt4 is a lot slower in backtesting.


Tenha um bom dia.


They said mt5 is faster. Cannot say have seen a difference yet in my backtesting but I guess it depends what you are doing.


There isn’t an 5 version at the moment, maybe later on if there’s more demand for it.


A very interesting article.


On Feb 23 2015, you gave the equations for p(win), p(lose) & p(open) in an answer to BYO2000. Most of it makes sense to me, but can you please explain how to arrived at the equations for p(win first) and p(lose first).


Certo. This is a conditional probability using standard theory.


If the price touched both the stop loss and the take profit during a time frame then.


there are two distinct probabilities with that set: Either it touched the SL first or it touched the TP first.


during that period. Hence the two different cases to count for this.


Great job, but I personally don’t trust that much the random walk theory. It states, that future princes are normally distributed and the probability to take each value depends on the standard deviation (volatility in this case.)


Based on that, how can big price fluctuations be explained ? For example, taking random walk as an absolute truth, it would be extremely bizarre to see prices fluctuations above 3ơ (3 times the volatility) since probability is less than 1% but if you look at the market it has happen quite a lot.


If you required the specific examples let me know I will show you.


I want to know your opinion about this, and if is possible, have an idea of how efficient is this strategy when you use it.


I completely get where you’re coming from. A lot of people – especially technical traders – don’t agree with the RWM. That’s their opinion. I am not going to spend a lot time defending it as there are people out there who can do a lot better job than I can. Though what I can say is that much of the criticism I’ve seen is unjustified or just plain wrong. What you say above only holds true if you assume that volatility and drift in the model never changes. Actually though these components are changing all the time.


Volatility measuring is by definition lagging so you can never know what the instantaneous volatility is. You can only estimate it based on information available at the time. So when you say a 3x volatility move, what that really means is 3x what the volatility was in the past. Not what it is at a given instant. This is a limitation of measurement not the model. As I mentioned in the article implied volatility can give you a forward measure and that can be used instead.


So far RWM is the best and simplest explanation of market moves I have yet seen. If something better comes along I’ll be the first to use it. I’ve seen advanced simulators and I can tell you that you can’t tell the difference between them and any other price chart – every type of chart pattern is seen and is reproducible. The word “random” just seems to be a red flag to a lot of people. But the RWM has both a deterministic and non-deterministic part and it’s the deterministic part we try to discover and trade on.


Hi can you explain how to upload new metatrader data in the excel spread sheet please? Thanks your help is appreciated.


I would be grateful if you could perhaps give a more detailed explanation as to how you calculated the “maximals” table (as used in your Excel Worksheet).


At first glance, it does seem to be related to some form of cumulative function of the “p(Yn=m)” probability you mention in the “Random Walk” explanation box – maybe some kind of cumulative distribution function, but it is not described here.


I read the related material and links provided about the “Random Walk”, as well as other sources of information by different authors, but can’t seem to find anything that would explain how you calculated the “maximals” table.


The maximals are a forecast of how far the price is expected to move (maximal distance) over a certain time. That’s taken from the random walk model with or without a drift component. The drift gives the trend so that allows the model to forecast changes in different directions (other than a flat market). There are standard mathematical procedures for working this out and creating a discrete time-based probability distribution from it. From that distribution it’s possible to work out the probability of a price move within a certain time interval.


There’s some more discussion about it here. Duke uni also has a lot of good info on this subject. The above papers are giving an overview.


There’s something I don’t understand. Your chances of winning are higher (let’s say 68.3% to cite your example), but the amount you would win is lower (26.9) than the amount you lose (-67.3).


This leads to a negative expected return:


So, if you run this strategy many times you’ll end up losing money, right?


You also have to account for the probability of the trade still being open. There’s an 8% probability that the price doesn’t reach either the stop or take profit and that accounts for the missing value in the expectation. So the value (1-0.683) in your formula doesn’t account for all other outcomes which have to be integrated over to find the true expectation. There’s always a finite probability that the trade will be open however long you wait. If you look at figure 5 for example the p(open) graph gets smaller but it never quite becomes zero. In either case this is a truth of computation – it’s not something that applies just to this strategy.


Indeed, the expected profitability of a trade if I am not mistaken should be an integral of an asymmetric capped maximal curve. Have you per chance made this computation in your testing, as I think this is the most relevant quantity to optimize on?


Another thing is that this is still very simplistic in the sense that the construction of your stop loss and take profit are based on how you built your signal. My understanding is that the signal you built is a simplistic version of something along this line: if you feel that the market is overselling an asset (downward trend) you will buy (hence the trend+ and trend - that were not very intuitive on the first reading). Then wanting to build your asymmetric maximal curve makes sense since you look at an asymmetric volatility which kind of tell you if the trend was fundamentally stopping and the future was noise, I can still expect the market to trend lower by x pips due to underlying volatility. I am not sure the way you measure it though makes sense given that in fact, what you want to look at is the volatility of the price if there were no trend going on, which will give you limit that will be breached quickly if the trend was to continue and the prediction was wrong. I feel this is in a sense a better way to include the potential signal into your stop loss, as the stop loss should then be tighter but on a justifiable note.


Overall I quite like the ideas you expose here, but I feel the main point which is the expected return computed from the integration of maximal curve is missing, as this is what is verifiable in live trading or backtest.


The more interesting question to me is the reverse hypothesis. That being the maximum likelihood estimator (MLE) of the trend and volatility given a noisy sequence of prices. Because without knowing this any expected return would in any case be zero when you cannot make any prior assumption on trend direction (the deterministic) and you have a symmetric range of probabilities. Solutions to the MLE can be found but that does mean using Monte Carlo simulation or something similar since there are no closed forms to this problem. This is something we are working on.


Does that indicator work on anything for e. g. on CFD or just forex?


It should work on most instruments including CFDs: Metals, Oil and so on. If you have any problems just raise a support request.


i think if you use rrr like this, this %82 tp probability also cant do any help for our accounts,


but may be this is what us new traders want to hear, wide stop loss and tight take profit, it is alluring for newbies.


özkan (izmir/ Turkiye)


Nobody here is recommending an sl or any other value.


The article is an analysis of the stop loss placement and what result that is having on your rr and on probability winning or losing the trade.


If you had read further than para one you would understand your remark has no logic but is the view of the amateur.


Great article-thanks very much. Is the spreadsheet still active so that historical data can be copied, or has it been protected since the last posts? I have Excel 2010 but there is no apparent way to paste data in the Input tab.


Yes it is still active. No, it’s not locked. But to edit you will need to save a local copy. This is because Excel 2010 and later will disable edits for any spreadsheets downloaded from the web. If you are still having an issue with this please use the contact form to get in touch and I’ll take a look.


Thanks, the problem seemed to be with Excel 2010. I tried 2013 and it works fine.


Hi, I was wondering how the maximal curves are built using estimated volatility. given 5m volatility of 10pips, so volatility for 24hr = s5*sqrt(24*60/12)=0.01697pips. Then for P(X>=TP) we can use z = (x-mu)/s24 and Pr(z>=(TP-mu)/s24), for TP=40pips and mu=0, im not getting 82%probability but 100%. I’m not sure this is the right way to do it. Wondering if you could point me to how to build those curves?


Please see reply below.


Hi, nice article I’m trying to understand it. I have a question about how sample volatility is used in the calculation of maximal curves.


Am i supposed to approximate the binomial dist with std normal using z=(x-mu)/s = x/s if mu=0, s=0.001 then calculate P(z>c) where c is TP. So if s5=0.0010 per 5m, we get 24hr volatility as s24=s5*sqrt(24*60/5)=0.01697, if target price is 40pips then is P(x>=.0040) or using z, P(z>=0.0040/s24) but this doesn’t give me 82% chance of reaching TP?


Further, doing this only gives me the prob of z being above c at the “end” of the holding period. but that’s not what we want, we want to find P(z>c) at any intermediate time? Would be great if you could explain.


It is a cumulative probability of maximal distance traversed in a certain time. So by that definition it covers all intermediate times between such as P(z>c) in your notation. I would also calculate the 24 hour volatility directly if that is what you need, rather than trying to scale up from 5M timeframes.


Excuse me Steve,


is this spreadsheet valid only for the EURUSD pair? I tried to use it with AUDUSD values but got thousands pips large TP and SL… While with EURUSD values it works perfectly.


Yes it is compatible with AUD/USD. This problem is most likely due mixed data histories. Please ensure all of the old data is removed and reset the “pip value” selector.


Alternative you can use the 4 indicator which is now available and does this for you:


This is a very detailed article and confirm to me what I thought when I approached the Forex market after a short period of trading. You mentioned at the end of the article that you have also an EA that make the same calculations of the TP/SL as your great Excel spreadsheet and I would be very happy to integrate it in my own EA used to trade.


Is it available for download free? Does it work on “live” data taken directly from 4 without the need to export them?


Thank you very much for your answer and for your website!


Yes it can work with a live price feed. It could be made available as an indicator in the future – but that would depend on the interest as it would need to be recoded.


is this spreadsheet valid only for the Pounds pair?


It should work with any pair. If you’re importing data from Metatrader please make sure the sizing is correctly set in the data tab.


Hi, I can`t paste right, I mean when I copy historical data from 4, and paste it to input as you said, there are no spaces between the comma, and it is not divided as on your picture. In your picture each cell gives one information like date, etc, but when I paste it the information starts in one cell and ends in another. I have new excel, what should I do?


If your data is all in one column as it sounds then you need to use the “text to column” function in Excel to format it into separate cells. If you saved it and opened it as a csv file it would normally do this for you.


One of the best articles I’ve found on stop and profit targets. Thanks for sharing your knowledge with a newbie like me!


problem with excel file can you upload it again?


You will need Excel 2010 or later otherwise some of the features will not work.


Hi, I can`t paste the same as you when I use data from 4. The numbers f. ex. start in one cell and end in the other. I have new excel. O que devo fazer?


That’s a very nice of you Mr. Steve. According to calculating volatility and RRR, I am wondering that as a day trader with a very short horizon period of investment. Ex. 5-15 Mins chart. This method could be potentially help any trades? Why I said so? What being said is that If I my trade set up were 2/1 RRR, which I have to set my SL at -200% and TP at +100%. In the long run, do you think this kind of statistic will help the trades to win? Literally, taking a smaller pips and widening a SL could really boost up a winning percentage which means that once I losses such any single trades I have to try to double up profitability to cover such losses. Here come to my question, in this kind of situation that I earlier mentioned, do you have any way to fix it? or if the theory you mentioned works, how could you adapt to use with scalping trader and day trader style?. Thank you very much for your consideration in advance.


It’s a good point and one I should have expanded on in the article. In my opinion it doesn’t make a lot of sense to have a fixed ratio of SL to TP for all cases. The choice should be dynamic because it depends entirely on the situation you are trading and the market conditions.


A breakout trade for example may have a low probability of success but a high payoff. As well it is usually clear after a short time whether the breakout is going to happen or not. In that case it doesn’t make much sense to allow say a 2:1 SL/TP which would allow a big drawdown. When in fact if the draw happens you already know the setup has failed. In other situations the reverse may be true.


Ótimo artigo. Can you explain why you calculate volatility on open/close data? “From the open/close data, I calculate that to be just over 10 pips per 5-minute period.” Why don’t you use the ATR or high/low data? I’m trading daily charts, so the difference is quite large.


You can use ATR. You can also use the Bollinger bandwidth as a vol measure. Whichever you use you should get roughly the same ratio of TP/SL however because the measures are relative to each other and not absolute. If you need to calculate a specific probability then in this case some calibration is needed depending on which vol metric is being used.


thank you for your good strategy . i have question : i tried to calculate probability for volatility of 10 pip per 5 min.


for 1 hour for distance 51. which gave us n=12 and m=6 for box formula. but i calculate 5% for probability and from your curves it seems true percentage is 15% can you tell me why my result are different ?


Your value seems too low. Because these are probability functions the curves need to be worked out as a cumulative value of the function (not the point value) over the move distance you are looking at.


Probably the best forex article I ever read.


Hi, very nice and useful article. I was wondering if it was possible to have a numerical example of how to calculate the probability using random walk. In your example, are you assuming a drift component=1? Or less?


Agradeço antecipadamente. Tchau.


“You can have the price rising then falling in which case it passes a TP AND SL. Por exemplo If you have very close TP/SL then these have near 100% chances of being hit.” If you imagine a space of outcomes you have.


P(Neither TP nor SL hit)”


EURNZD, EURAUD, EURGBP, EURCAD whipsaw upwards before collapsing. The greatest one was the EURGBP this time round.


(One either widens their SLs 150-200pips for crosses or tightened stops risked a larger loss when it hits the SL. Other than staying out completely.


Prior to ECB, EURCAD went to low of 1.36945. The whipsaw touched SL of 1.3765 before retracing downwards. For a short position, adding a Stop Loss gave away profit of 70 pips. Does assigning probability described applies to risk events like ECB?


(The EURGBP is now back at the same level, though it whipsawed the most. )


What’s your view about contrarian trades (that agrees with TA at the time you look at it)? example would you have longed the EURNZD on Mar 5, would using this probability analysis tell one not to long but short it instead although the charts are long – Measuring the strength/continuity of reversal moves.


-Does assigning probability described applies to risk events like ECB?


Not unless these events occur frequently within the time sample you are looking at, but even then its unlikely you could ever model them to predict an outcome. Major news releases – those with very high impact – are by their nature unpredictable and can/will change the trajectory of the price in ways that are beyond normal statistically analysis.


-What’s your view about contrarian trades (that agrees with TA at the time you look at it)? example would you have longed the EURNZD.


Absolutely, contrarian trades can and do work – but then there are limits, I would be cautious about trading contrarian against strong fundamentals. For eg, I wouldn’t long EURNZD – simply because of the swap yield of -4.24% on the long side. The strong downward trend for the last six years is a reflection of that. But then if you’re scalping a few pips here and there it can make sense, and sure the Euro is going to turn sooner or later.


The maximal curves show the probability of how many pips price will move in /either/ direction right? I don’t quite get how the curves can be applied to just TP. por exemplo. if we want to know the probability of TP of +40 pips in 24hrs, yes the curves do give a probability of 82%, but wouldn’t it be 40 pips in either direction? ie. 41% of +40 pips & 41% of -40 pips? (because I’m assuming the curves have no drift, a walk in either direction is equally likely, etc.) Maybe I’m missing something – apologies if it’s a dumb question. Obrigado!


No only in one direction. The maximal curve will give the probability of a maximum point being reached, or equally if you apply the formula on the other side, to a minimal point being reached. When symmetric as you say, it is just mirrored.


So for eg: P(Z>+40 pips) gives an independent probability only of the price moving above the +40 pips level. It says nothing about the price falling say 200 pips below, this is why there is a separate case for the SL point.


With no drift, yes it would be the same (41% for a move either side).


(apologies again, I’m a bit slow) let’s see if I got this. The SL is a separate case.


So just considering the TP, what the maximal curve shows is P(Z>+40pips) + P(Z+40pips) = 41% ?


Not quite. What the maximal curve basically shows is the probability of a high-watermark being reached – and that applies for a certain time period only. So say you want to know the probability of the price going +40 pips or higher within 24 hours. That’s P(Z>+40 pips) from the 24-hour curve & it’s 82%. After 1 hour, its 28% (thereabouts, I am just looking at chart not in Excel.)


Thanks for your patience Steve 🙂


It was probably my fault, but my previous comment was strangely truncated. What I wrote was to ask if the maximal curves show: P(Z>+40pips) + P(Z+40pips)=82%. If so, doesn’t that also imply P(Z<-40pips)=82%, which surely cannot be? I'm lost here.


Você é bem vindo.


I have to answer here because its not possible to add a reply any deeper (it will be better to continue this in Forum section where there is more room.):


–What I wrote was to ask if the maximal curves show: P(Z>+40pips) + –P(Z+40pips)=82%.


There is no addition here (did you mean P[Z 40pips, it gives this as 82% from the curve. This tells me only one thing in isolation: that the TP has 82% chance of being struck.


Very cool idea & great article! I have some questions. In Step 3, can you explain how you got the table for p(win), p(loss), p(open)? Obrigado!


Certo. It’s standard probability theory:


Say p(wl) = P(price hits SL & TP)


P(wl) = p(TP hit) x p(SL hit)


p(win first) = p(TP hit) x p(wl) / ( p(TP hit) + p(SL hit) )


p(lose first) = p(SL hit) x p(wl) / ( p(TP hit) + p(SL hit) )


p(win)=p(TP hit) – p(lose first)


p(lose)=p(SL hit) – p(win first)


Thanks Steve. I love your articles.


Could you commend on reversal moves? Trades such as EURAUD on 20 Feb hit a low of 1.4385 and spiked upwards to 1.4583.


100-200 pips reversed moves can be pretty tough psychologically to place stops – where you don’t want them too close, yet when it hits SL it erased off those hard earned gains or puts one in steeper losses.


I was in some other trades that reversed off its lows. As I read your posts, I know we are going down to really precise levels now. That -100+ stoploss can take place in a very short span of time and hurt quite a bit if one’s position is in several trades at the same time.


EUR/AUD is quite a volatile pair, with about 50% higher volatility than EUR/USD at the moment.


That is for a 1 day trade, for the short side I would use a ratio somewhere around TP=56/SL=250. Are you trading the long or short side because it really makes a difference here. On the buy side there’s very high swap rate (-3.13%) to take into consideration.


Reversal moves are all part of the normal daily volatility in the markets. I’m of the view that it’s better to have a lower leverage so that these events can be withstood – because in the scheme of things a 100-200 pip move is pretty insignificant really.


Obrigado. I was thinking through my mistakes, and reading your spreadsheets. Essentially the trades I got stopped out was GBPUSD, GBPCAD, EURCAD. It is trade timing.


SL=250 is tough psychologically (I am not going to be able to test 200 plus pips.)


Actually some profit from the EURAUD, EURNZD. I trade several illuid pairs gbpnzd and also trade short side for some pairs, and hedge sometimes as well.


I will look through the win loss ratios, and trades probabilities to examine the trades and see if I can improve on where it went wrong. You have got a great resource. I was already doing breakouts, grid trading, carry trades for some time, but I still come back because everything was very well written and learn from someone who is strong.


Could you write an article on basket trading? I have been practicing, don’t know if this is something doable on a live account.


nice idea! thanks steve, i will try this out and see how it works.

Комментариев нет:

Отправить комментарий