Friday 14 July 2017

Gaussian Moving Average Afl


Uma biblioteca de funções para a filtragem e recuperação de informações de curvas de preços, desde a análise técnica tradicional até a transformação mais avançada e as estatísticas funcionam médias móveis, osciladores, bandas, momentum, índices de força, regressão linear, Hilbert transforma, Ehlers indicadores e análise espectral. Os indicadores são listados em ordem alfabética Os indicadores tradicionais utilizam a biblioteca de indicadores TA-Lib de Mario Fortier que se estabeleceu como um padrão As informações sobre o uso, os algoritmos eo código fonte dos indicadores TA-Lib podem ser encontradas on-line no Fonte também está incluído na pasta Fonte Zorro O código fonte da maioria dos outros indicadores e funções de análise podem ser encontrados em Zorro incluem indicadores c Filtros espectrais e funções de análise de freqüência de amplitude estão listados na biblioteca espectral Padrões de vela clássica podem ser encontrados na biblioteca de padrões. AC vars Dados var. Accelerator Oscilador a diferença do indicador AO ver belo W e sua média móvel simples de 5 barras SMA Acredita-se para indicar a aceleração e a desaceleração de uma força motriz do mercado o que quer que meios Para dados normalmente um MedPrice ou série do preço é usado Código de fonte nos indicadores c. Accumulation Distribuição Oscilador Close-Low - High-Close Alto-Baixo Varia de -1 quando o fechamento é a baixa da barra, para 1 quando é a alta Suposto calibrar a oferta ea demanda, determinando se os comerciantes estão geralmente acumulando compra ou distribuição de vendas Este indicador foi publicado em muitas variantes individuais para A fórmula, mas nenhum deles parece melhor do que o outro Usa a série de preços de ativos atuais Código-fonte em indicadores c. ADX int TimePeriod var. Uma Indicação de Movimento Direcional Média móvel do indicador DX Veja abaixo Usa a série de preços de ativos atual Não Support TimeFrame Os valores retornados variam de 0 a 100.ADXR int TimePeriod var. Average Direcional Movimento Index Rating A média do atual ADX eo ADX de Tim EPeriod barras atrás Usa a série de preços de ativos atual Não suporta TimeFrame. Alligator vars Dados var. Alligator Indicador Consiste em três linhas de azul SMA 13 adiada por 5 barras SMA vermelho 8 adiada por 2 barras de verde SMA 5 Indica uma tendência de queda com as linhas na Ordem azul-vermelho-verde de cima para baixo e uma tendência de alta com verde-vermelho-azul Quanto mais próximas as linhas do jacaré se movem, mais fraca fica a tendência e vice-versa Não contém o atraso adicional de 3 barras do algoritmo original 3 para isso Para os dados normalmente a média baixa alta MedPrice série é usada Resultado em rRed rGreen rBlue Código fonte em indicadores c. ALMA vars Dados, int TimePeriod, int Sigma, var Desvio var. ALMA vars Dados, int TimePeriod var. Arnaud Legoux Moving Média Baseado em uma distribuição gaussiana com um viés para o início da série de dados, ou seja, preços mais recentes Parâmetros Sigma largura distribuição, padrão 6 Offset bias factor, padrão 0 85 Código fonte em indicadores c. AO vars Dados var. Awesome Oscilador Simplesmente a diferença de um SMA de 5 barras e um de 34 barras SMA Para dados normalmente um MedPrice ou série de preços é usado Código-fonte em indicadores c. APO vars Dados, int FastPeriod, int SlowPeriod, int MAType var. Absoluto Preço Oscilador um mais geral Versão do AO Retorna a diferença entre duas médias móveis Parâmetros FastPeriod Número de período para o MA rápido, SlowPeriod Número de período para o MA lento, MAType Tipo de Moving Average. Aroon int TimePeriod var. Aroon indicador Consiste em duas linhas para cima e para baixo Que medem quanto tempo tem sido desde o mais alto mais alto mais baixo baixo ocorreu dentro do período de tempo Usa a série de preços de ativos atual Não suporta TimeFrame Resultado em rAroonDown rAroonUp. AroonOsc int TimePeriod var. Aroon Oscilador Calculado subtraindo o Aroon Down do Aroon Up O valor de retorno irá oscilar entre 100 e -100 Utiliza a série de preços de activos actual Não suporta TimeFrame. ATR int TimePeriod var. Average True Range Uma medida da volatilidade dos preços Fórmula ATR ATR1 TimePeriod-1 max Alta, Close - min Low, Close TimePeriod onde ATR1 é o ATR da última barra Utiliza os preços de ativos atuais A função cria internamente séries quando TimeFrame é 1 e deve Em seguida, ser chamado em uma ordem fixa no script Ver também Volatilidade CVolatilty TrueRange ATRS. ATR vars Open, vars Alto, vars Baixo, vars Fechar, int TimePeriod var. Average True Range de arbitrária série de preços, com offset arbitrário e frame. ATRS tempo Int TimePeriod var. Simple Average True Range SMA do TrueRange sobre o TimePeriod usando a série de preços de ativos atual Uma medida da volatilidade de preços, mais simples de calcular do que o ATR, mas adaptando lenta às mudanças de volatilidade e, portanto, A plataforma MT4 em vez do real ATR Não suporta TimeFrame Código-fonte em indicadores c. AvgPrice var. Average Preço Simplesmente Open High Low Fechar 4 com o preço do activo atual series. BBands v Ars Data, int TimePeriod, var NbDevUp, var NbDevDn, int MAType. Bollinger Bands Consiste em três linhas a banda média é uma média móvel simples geralmente 20 períodos do preço típico TP As faixas superior e inferior são n desvios padrão geralmente 2 acima e Abaixo da banda média As bandas se alargam e estreitam quando a volatilidade do preço é maior ou menor, respectivamente Bandas de Bollinger indicam quando o preço se tornou relativamente alto ou baixo, o que é sinalizado através do toque ou menor penetração da linha superior ou inferior Em rRealUpperBand rRealMiddleBand rRealLowerBand Parâmetros NbDevUp Desvio multiplicador para banda superior, NbDevDn Desvio multiplicador para banda inferior, MAType Tipo de Moving Média Exemplo em Indicatortest c. BBOsc vars Dados, int TimePeriod, var NbDev, int MAType var. Bollinger Bandes Oscilador a percentagem do Valor atual da série dentro do Bollinger Bands. Beta vars Dados, vars Data2, int TimePeriod valor var. Beta Uma medida de um único ass E s preços versus o índice global do mercado O preço do ativo é dado em Data e os preços de mercado são dados em Data2 O algoritmo calcula a mudança entre os preços em ambas as séries e, em seguida, traça essas mudanças como pontos no plano Euclidiano O valor x de qualquer ponto É a mudança de mercado de Data2 eo valor de y é a mudança de recurso de dados O valor de beta é a inclinação de uma linha de regressão linear através destes pontos Um beta de 1 é simples a linha yx, então o ativo varia percisely com o mercado A beta de menos Do que um significa que o ativo varia menos do que o mercado e um beta de mais de um significa que o ativo varia mais do que o market. Balance Of Power simplesmente Close - Open High - Low Usa o atual preço do ativo series. CCI int TimePeriod varmodity Channel Variação Índice Do preço de sua média estatística, normalmente oscila entre -100 Usa a série de preços de ativos atual Não suporta TimeFrame. CI int TimePeriod var. Choppiness Índice mede a volatilidade de barra única em relação ao Volatilidade do TimePeriod passado em um intervalo de 1 100 Usa a série de preço de ativos atual Não suporta TimeFrame. ChandelierLong int TimePeriod, var Multiplicador var. ChandelierShort int TimePeriod, var Multiplier var. Chandelier sair do preço mais alto de TimePeriod menos o ATR multiplicado com Multiplier Normalmente usado como um Stop Loss parar de manter negociações em uma tendência e impedir uma saída antecipada, enquanto a tendência continua Código-fonte em indicadores c Não suporta TimeFrame Exemplo no TMF chapter. CGOsc vars Dados, int TimePeriod var. Center of Gravity Oscilador, por John Ehlers calcula o desvio dos preços de seu centro dentro do TimePeriod Pode ser usado para identificar pontos de viragem de preço com quase zero lag Código-fonte em indicadores c. Chikou int Shift var. Chikou linha pertencente ao indicador Ichimoku simplesmente o Close deslocado Forward by Shift default opcional 26 Usa a série de preços de ativos atual Código-fonte em indicadores c. CMO vars Dados, int TimePeriod var. Chande M Omentum Oscilador Semelhante ao RSI, mas divide o movimento de dados totais pelo movimento líquido para cima - para baixo para cima para baixo. Coral vars Dados var. Coral Indicator, simplesmente um T3 com TimePeriod 60 e VolumeFactor 0 4.Correlation vars Dados1, vars Data2, int TimePeriod Var. O coeficiente de correlação de Pearson entre duas séries de dados sobre o dado TimePeriod no intervalo entre -1 1 Um coeficiente de 1 0, uma correlação positiva perfeita, significa que as mudanças em Data2 causam mudanças idênticas em Data1 ega mudança no indicador resultará em Uma mudança idêntica no preço do ativo Um coeficiente de -1 0, uma correlação negativa perfeita, significa que as mudanças no Data2 causam mudanças idênticas no Data1, mas na direção oposta Um coeficiente de zero significa que não há relação entre as duas séries e que a A alteração em Data2 não terá efeito sobre Data1 Esta função também pode ser usada para obter a autocorrelação de uma série calculando o coeficiente de correlação entre a série original e o mesmo ser Vias Data1, vars Data2, int TimePeriod var. Covariance entre duas séries de dados Pode ser usado para gerar uma matriz de covariância fi para o cálculo de fronteira eficiente de markowitz. DChannel int TimePeriod. Donchian Canal o valor mínimo e máximo das funções priceHigh e priceLow durante o período de tempo Base do famoso sistema de negociação de tartaruga Usa a série de preço de ativos atual Não suporta TimeFrame Resultado em rRealUpperBand rRealLowerBand. DCOsc vars Dados, int TimePeriod var. Donchian Channel Oscillator the Porcentagem do atual valor de dados dentro do canal de Donchian Usa o atual ativo e atual TimeFrame. Decycle vars Dados, int CutOffPeriod var. Ehlers Decycler, um indicador de tendência de baixa lag simplesmente Dados - Dados HighPass2, CutOffPeriod Remove todos os ciclos abaixo de CutOffPeriod dos dados Série e mantém a tendência A função cria internamente séries e, portanto, deve ser chamado em uma ordem fixa no script Source cod E em indicadores c. DEMA vars Dados, int TimePeriod var. Double Exponencial Média Móvel. DPO vars Dados, int TimePeriod var. Detrended Price Oscilador acredita-se para detectar mudanças antecipadas na direção de preços DPO Dados 0 - SMA Dados n 2 1, n onde n É o TimePeriod Código fonte em indicadores c. DX int TimePeriod var. Directional Índice de movimento por Welles Wilder que, a propósito, descobriu que a interação do sol, lua e terra é a base de todo o movimento do mercado Em caso de que o sol, a lua , E terra de repente se abstêm de mover o mercado, ele também inventou alguns indicadores tradicionais O DX é acreditado para indicar tendência de força Os valores variam de 0 a 100, mas raramente ficam acima de 60 O DX usa a série de preços de ativos atual e não suporta TimeFrame Fórmula DX 100 abs PlusDI-MinusDI PlusDI MinusDI Para PlusDI e MinusDI veja a descrição abaixo. VAR Dados, int TimePeriod var. EMA vars Dados, var alpha var. Exponential Média Móvel Enfatiza valores de dados mais recentes Usa a fórmula E MA dados alfa 1-alfa EMA1 onde alfa é um fator de recursividade entre 0 1 que é calculado a partir de 2 0 TimePeriod 1 e EMA1 é o valor EMA anterior Quanto menor for o alfa, maior será o efeito de alisamento da fórmula EMA Algoritmos ligeiramente diferentes A primeira usando um TimePeriod não cria uma série, é mais lenta, e requer um comprimento de dados de TimePeriod UnstablePeriod 1 O segundo usando alfa cria uma série interna, precisa apenas de um comprimento de dados de 2 e é muito mais rápido. Var. Fisher Transform transforma uma série de dados normalizada para um intervalo distribuído normal O valor de retorno não tem limite teórico, mas a maioria dos valores está entre -1 1 Todos os valores de dados devem estar no intervalo -1 1, fi normalizando com o AGC Normalize ou Cdf function O comprimento de dados mínimo é 1 Fonte disponível em indicadores c. FisherInv vars Dados var. Inverse Fisher Transform comprime a série de dados entre -1 e 1 O comprimento mínimo da série de dados é 1 Source availa Indicadores de entrada c. FisherN vars Dados, int TimePeriod var. Fisher Transformar com normalização normaliza a série de dados com o dado TimePeriod e, em seguida, transforma-lo para um intervalo distribuído normal semelhante a um filtro normalizar ver abaixo, mas mais seletivo devido à distribuição normal Da saída O valor de retorno não tem limite teórico, mas a maioria dos valores está na faixa -1 5 1 5 O comprimento mínimo da série Data é igual a TimePeriod A função cria internamente séries e, portanto, deve ser chamado em uma ordem fixa no Script Fonte disponível em indicadores c. FractalDimension vars Dados, int TimePeriod var. Fractal dimensão da série Data, por John Ehlers normalmente 1 2 Menores valores significam mais jaggies Pode ser usado para detectar o regime de mercado atual ou adaptar médias móveis para as flutuações De uma série de preços Fonte disponível em indicadores c. FractalHigh vars Dados, int TimePeriod var. Fractal High, um indicador de Bill Williams, acreditado para sinalizar quando o mercado inverte Não tem nada a ver com fractals Retorna o valor de dados mais alto quando ele está no centro do TimePeriod caso contrário 0.FractalLow vars Dados, int TimePeriod var. Fractal Low Retorna o menor valor de dados quando ele está no centro do TimePeriod caso contrário 0. Gauss vars Data, int Filtro TimePeriod var. Gauss, retorna uma média ponderada dos dados dentro do período de tempo determinado, com a curva de peso igual à distribuição normal de Gauss Útil para remover o ruído por alisamento de dados brutos O comprimento mínimo da série de dados é Igual a TimePeriod o atraso é metade do TimePeriod. HAClose var. Haiken Ashi preços, com base nos preços dos ativos atuais Código-fonte em indicadores c Alternativamente, a curva de preços pode ser convertido em Haiken Ashi barras usando a barra function. HH int TimePeriod, int Offset Var. Alto valor da função priceHigh sobre o TimePeriod terminando com Deslocamento default 0 F i HH 3 retorna o preço mais alto das últimas 3 barras Utiliza a série preice de ativos atual Não suporta TimeFra Me para quadros de tempo múltiplos, use MaxVal High Offset, Período com um tempo sincronizado High série em vez Ver também dayHigh. HMA vars Dados, int TimePeriod var. Hull Moving Average por Alan Hull tenta abordar lag, bem como para suavizar alguns choppiness Fórmula HMA n WMA 2 WMA n 2 WMA n, sqrt n A função cria internamente uma série e, portanto, deve ser chamado em uma ordem fixa no script Código-fonte em indicadores c. HTDcPeriod vars Dados var. Hilbert Transformar - Período de Ciclo Dominante, desenvolvido por John Ehlers Algoritmos de transformação de Hilbert são explicados no livro de Ehler Ciência de foguetes para comerciantes ver a lista de livro Esta função é equivalente, mas menos exato do que o DominantePeriod função. HTDcPhase vars Dados var. Hilbert Transform - Ciclo Dominante Phase. HTPhasor vars Dados var. Hilbert Transform - Phasor Components Resultado em rInPhase rQuadrature. HTSine vars Dados var. Hilbert Transform - SineWave Resultado em rSine rLeadSine. HTTrendline vars Dados var. Hilbert Transform - Instantâneo Trendline. HTTr EndMode vars Dados int. Hilbert Indicador de tendência de transformação - retorna 1 para o modo de tendência, 0 para Cycle Mode. Hurst vars Dados, int TimePeriod var. Hurst expoente da série de dados entre 0 1 O expoente Hurst mede a memória de uma série Ele quantifica a Autocorrelação, ou seja, a tendência para reverter para a média Hurst 0 5 ou para continuar tendendo em uma direção Hurst 0 5 Desta forma, o expoente Hurst pode detectar se o mercado está em um estado de tendência A janela TimePeriod mínimo 20 deve ter comprimento suficiente para capturar A tendência de longo prazo A função cria internamente uma série e, portanto, deve ser chamado em uma ordem fixa no script Fonte disponível em indicadores c. Ichimoku int PeriodTenkan, int PeriodKijun, int PeriodSenkou, int Offset. Ichimoku Kinko Hyo indicador Inventado pelo jornalista Goichi Hosoda em 1930 Uma mistura dos preços médios de 3 períodos de tempo acredita-se para dar uma visão profunda sobre as tendências do mercado devido ao seu enorme número de linhas coloridas Offset default 0 determina a barra para c Alcuando o indicador Retorna 4 variáveis. Uma outra linha pertencente ao Ichimoku, a linha Chikou, é peeking no futuro e calculada separadamente Usa a série de preços de ativos atuais A função cria internamente séries quando TimeFrame é 1 e deve então ser chamado em uma ordem fixa no Script Código fonte em indicadores c. Internal Bar Força simplesmente Close - Low High - Low Usa a série de preço atual do ativo. KAMA vars Dados, int TimePeriod var. Kaufman Média móvel adaptativa Uma média móvel exponencial ajustada pela volatilidade de preços, portanto, seu período de tempo se torna Mais curto quando a volatilidade é alta. Keltner vars Data, int TimePeriod, var var. Keltner Channel, por Charles Keltner A Simple Moving Average - SMA Data, TimePeriod - com bandas laterais na distância Factor ATRS TimePeriod Resultados em rRealUpperBand rRealMiddleBand rRealLowerBand Código fonte in Indicadores c. Laguerre vars Dados, var alpha var.4-elemento Filtro Laguerre Utilizado para suavizar dados semelhantes a um EMA mas com menos atraso e um wi De gama de sintonização dada pelo factor de alisamento alfa 0 1 Os componentes de baixa frequência são retardados muito mais do que os componentes de alta frequência, o que permite filtros muito suaves com apenas uma pequena quantidade de dados O comprimento mínimo da série de dados é 1, Período é 4 A função cria internamente séries e, portanto, deve ser chamado em uma ordem fixa no script Fonte disponível em indicadores c. LinearReg vars Dados, int TimePeriod var. Linear Regressão, também conhecido como método de mínimos quadrados ou melhor ajuste tentativas de regressão linear Para ajustar uma linha de tendência reta entre vários pontos de dados de tal forma que a distância entre cada ponto de dados ea linha de tendência é minimizada Para cada ponto, a linha reta sobre o período de barra anterior especificado é determinada em termos de ybmx A função LinearReg retorna bm TimePeriod -1 Para regressão de ordem superior, use as funções de polinômio politápico Para a regressão logística com múltiplas variáveis, use a função aconselhar PERCEPTRON. Linha ArRegAngle vars Dados, int TimePeriod var. Linear Ângulo de regressão Retorna m convertido em graus Devido às diferentes unidades xey de um gráfico de preços, o ângulo é normalmente de pouco uso, exceto talvez para os seguidores Gann. LinearRegIntercept vars Data, int TimePeriod var. Linear Regressão Interceptação Retorna b. LinearRegSlope vars Dados, int TimePeriod var. Linear Regressão Inclinação Retorna m como diferença de preço por bar. LL int TimePeriod, int Desvio var. Lowest valor da função priceLow sobre o TimePeriod terminando com Offset default 0 F i LL 3,10 retorna o preço mais baixo entre as últimas 10 e as últimas 13 barras Utiliza a série de preços de ativos atual Não suporta TimeFrame para quadros de tempo múltiplos, use MinVal Low Offset, Período com uma série de tempo sincronizado Low Veja também dayLow. MACD Vars Data, int FastPeriod, int SlowPeriod, int SignalPeriod. Moving Média Divergência de Convergência O MACD é um indicador de tendência a médio prazo, criado subtraindo-se um período 26 Exponential Moving Ave Rage EMA ver acima de um EMA de 12 períodos Um EMA de nove períodos é então aplicado ao resultado do MACD para criar uma linha de sinal A linha do Histograma do MACD é finalmente criada a partir da diferença do MACD para a sua linha de sinal Acredita - Cruzamento do histograma a partir de baixo é um sinal de compra, cruzamento de zero acima de um sinal de venda A fórmula é. rMACD EMA Dados, FastPeriod - MEM Data, SlowPeriod rMACDSignal EMA rMACD, SignalPeriod rMACDHist rMACD - rMACDSignal. Resultados em rMACD rMACDSignal rMACDHist Retorna rMACD Parâmetros FastPeriod período de tempo para o MA rápido, SlowPeriod período de tempo para o lento MA, SignalPeriod período de tempo para suavizar o sinal line. MACDExt vars Dados, int FastPeriod, int FastMAType, int SlowPeriod, int SlowMAType, int SignalPeriod, int SignalMAType. MACD com controlável Tipo MA Resultado em rMACD rMACDSignal rMACDHist Parâmetros FastPeriod período de tempo para o MA rápido, FastMAType Tipo de média móvel para MA rápida, SlowPeriod período de tempo para o MA lento, SlowMAType Tipo de Média Móvel para MA lento, período de tempo SignalPeriod para suavizar a linha de sinal, Tipo de sinal Tipo de Média Móvel para linha de sinal. MACDFix vars Dados, int SignalPeriod. Moving Média Convergência Divergência Fix 12 26 Resultado em rMACD rMACDSignal rMACDHist Parâmetros SignalPeriod período de tempo para Suavizando a linha de sinal. MAMA vars Dados, var FastLimit, var SlowLimit. MESA Média Movente Adaptativa, desenvolvido por John Ehlers ver links Resultado em rMAMA rFAMA Parâmetros FastLimit Uso de limite superior no algoritmo adaptativo, SlowLimit Limite inferior de uso no algoritmo adaptativo. MaxVal Vars Data, int TimePeriod valor var. Highest sobre um período especificado. MaxIndex vars Dados, int TimePeriod int. Index de maior valor durante um período especificado 0 valor mais alto está na barra atual, 1 em uma barra atrás, e assim por diante. Median vars Data, int TimePeriod var. Median Filtro classifica os elementos da série de dados e retorna seu valor médio dentro do período de tempo útil Útil para remover picos de ruído por eliminat Ing valores extremos O comprimento mínimo da série Data é igual a TimePeriod o atraso é metade do TimePeriod Veja também Percentile. MedPrice var. Center preço simplesmente o ponto central High Low 2 da vela atual Para o preço médio - a média de todos os preços Ticks da vela - use price. MidPoint vars Dados, int TimePeriod var. MidPoint sobre período Simplesmente mais alto valor menor valor 2.MidPrice int TimePeriod var. Midpoint preço sobre período Simplesmente mais alto mais baixo mais baixo 2 da série de preços de ativos atual Não suporta TimeFrame. MinusDI int TimePeriod var. MinusDI vars Aberto, vars Alto, vars Baixo, vars Fechar, int TimePeriod var. Minus Indicador Direcional, uma parte do indicador DX Se a função não for chamada com diferentes séries de preços, a série de preços de ativos atuais É usado. MinusDM int TimePeriod var. MinusDM vars Aberto, vars Alto, vars Baixo, vars Fechar, int TimePeriod var. Minus Direcional Movimento, duas versões Se a função não é chamado com diferentes séries de preços, a corrente a Sset série de preços é usado. MinVal vars Dados, int TimePeriod valor var. Lowest sobre um período especificado. MinIndex vars Dados, int TimePeriod int. Index de menor valor durante um período especificado 0 menor valor está na barra atual, 1 a uma barra atrás , E assim por diante. MinMax vars Dados, int TimePeriod valores var. Lowest e mais alto e seus índices durante um período especificado Resultado em rMin rMax rMinIdx rMaxIdx. MinMaxIndex vars Dados, int TimePeriod int. Indexes de valores mais baixos e mais altos durante um período especificado Resultado Em rMinIdx rMaxIdx 0 barra atual, 1 um bar atrás, e assim por diante. MMI vars Dados, int TimePeriod var. Market Meanness Index por Financial Hacker Mede a maldade do mercado, ou seja, sua tendência de reversão média, em uma faixa de 0 100 números aleatórios Têm um MMI de 75 Os preços reais são mais ou menos autocorrelacionados, então a probabilidade de uma série de preços reais reverter para a média é inferior a 75, mas normalmente mais de 50 Quanto mais alto, mais ruim é o mercado O Market Meanness Index Pode determinar quando a tendência Os sistemas que se tornam mais rentáveis ​​MMI está caindo ou menos rentável MMI está subindo, e assim evitar perdas em períodos não lucrativos Código fonte em indicadores c. Mom vars Dados, int TimePeriod var. Momentum Simples Dados 0 - Data TimePeriod Veja também diff. Moment vars Data, int TimePeriod, int N var. O momento estatístico N 1 4 da seção de séries de dados dada por TimePeriod O primeiro momento é a média, o segundo é a variância, o terceiro é skewness ea quarta ist kurtosis Fonte disponível nos indicadores c. MovingAverage vars Dados, int TimePeriod, int MAType var. Moving média Parâmetros MAType Tipo de Moving Average, ver observações. MovingAverageVariablePeriod vars Dados, vars Períodos, int MinPeriod, int MaxPeriod, int MAType var. Moving média com período variável dado pela série Períodos Parâmetros MinPeriod Valor menor que mínimo será alterado para Período mínimo, MaxPeriod Valor maior que máximo será alterado para Período máximo, MAType Tipo de média móvel, ver observações. NATR Int TimePeriod var. Normalized Average True Range, por John Forman Semelhante ao ATR, exceto que está sendo normalizado da seguinte forma NATR 100 ATR TimePeriod Feche Utiliza a série de preços de ativos atual Não suporta TimeFrame. Normalize vars Data, int TimePeriod var. Transforms the As séries de dados para a faixa -1 1 dentro do dado TimePeriod Semelhante à função AGC, mas não diferencia entre ataque e decaimento O comprimento mínimo da série Data é igual a TimePeriod Fonte disponível nos indicadores c Consulte também scale. NumInRange vars Low, Vars High, var Min, var Max, int Comprimento var. Number de intervalos de dados, dados pelos seus valores Low e High, que se encontram completamente dentro do intervalo de Min para Max dentro do comprimento dado Pode ser usado para calcular a distribuição de preços ou Velas Baixa e Alta podem ser configuradas para o mesmo valor para contar todos os valores no intervalo ou trocadas para contar todas as velas que tocam no intervalo Faixa Fonte disponível nos indicadores c. NumRiseFall vars Dados, int T ImePeriod var. Length da seqüência atual de valores ascendentes ou descendentes na matriz de dados, de volta ao dado TimePeriod Para uma seqüência crescente seu comprimento é retornado, para uma seqüência de queda o comprimento negativo Range resp -1 - TimePeriod Fonte disponível nos indicadores c Veja o script RandomWalk e o capítulo Estratégia para um exemplo Fonte disponível nos indicadores c. NumWhiteBlack var Corpo, int Deslocamento, int TimePeriod var. Número de velas brancas menos negros no dado TimePeriod Deslocamento é a distância para a barra atual 0 barra atual, Corpo é o comprimento mínimo de uma vela a ser contada Fonte disponível em indicadores c. Percentile vars Dados, int Comprimento, var Percent var. Returna o percentil dado da série de dados com dado Length fi Percentagem 95 retorna o valor de dados que está acima de 95 De todos os outros valores A porcentagem 50 retorna a mediana da série de dados Para calcular a porcentagem de um determinado valor de percentil, use a função NumInRange e conte os elementos abaixo do percentil. PlusDI int TimePeriod var. PlusDI vars Abrir, vars Alto, vars Baixo, vars Fechar, int TimePeriod var. Plus Indicador Direcional, uma parte do indicador DX, duas versões Na primeira versão, a série atual de preços de ativos é usada. PlusDM int TimePeriod Var. PlusDM vars Aberto, vars Alto, vars Baixo, vars Fechar, int TimePeriod var. Plus Direcional Movimento, duas versões Na primeira versão a série de preço atual do ativo é used. PPO vars Dados, int FastPeriod, int SlowPeriod, int MAType var. Perentage Price Oscillator Parâmetros FastPeriod Número de período para o MA rápido, SlowPeriod Número de período para o MA lento, MAType Tipo de Moving Average. ProfitFactor vars Data, int Comprimento var. Returns o fator de lucro da série de dados O fator de lucro é o Relação da soma dos retornos positivos ie Dados i-1 Dados i para a soma de retornos negativos ie Dados i-1 Dados i O valor retornado é cortado para a faixa 0 1 10 Seu recíproco deve ser usado quando a matriz de dados está em não Em ordem de série, mas em cronolo Gual, como as vitórias e perdas são então trocados Fonte disponível em indicadores c. ROC vars Dados, int TimePeriod var. Rate de mudança, 100 escala price-prevPrice prevPrice 100.ROCP vars Dados, int TimePeriod var. Rate de mudança Porcentagem preço - PrevPrice prevPrice Veja também diff. ROCR vars Dados, int TimePeriod var. Rate da taxa de alteração preço prevPrice. ROCL vars Dados, int TimePeriod var. Logarithmic retorno log preço prevPrice. ROCR100 vars Dados, int TimePeriod var. Rate de taxa de mudança, 100 escala Preço prevPrice 100.Roof vars Dados, int CutoffLow, int CutoffHigh var. Ehler s filtro de telhado, prepara a série de dados para computação adicional, removendo tendência e ruído Aplica um filtro passa-alto de 2 pólos seguido do filtro suave Valores recomendados para o baixo e Os períodos de corte de alta são 10 e 50 O comprimento mínimo da série de dados é 2 A função cria internamente séries e, portanto, deve ser chamado em uma ordem fixa no script Fonte disponível em indicadores c. RSI vars Dados, int TimePeriod var. Rela Por Welles Wilder Relação do movimento de dados ascendente recente para a faixa total de movimento de dados 0 100 O RSI é acreditado para indicar condições de sobre-venda de sobrevenda quando o valor é mais de 70 abaixo 30 Formula RSI 100 Up Up Dn onde Up EMA max 0 , Data 0 - Data 1, TimePeriod e Dn EMA max 0, Data 1 - Data 0, TimePeriod. RVI int TimePeriod var. Relative Vigor Index, por John Ehlers Razão de mudança de preço para a faixa de preço total CO HL média durante o período de tempo E suavizada com um filtro FIR Oscila entre -1 e 1 A função cria internamente uma série e, portanto, deve ser chamado em uma ordem fixa no script Código-fonte em indicadores c. SAR var Etapa, var Min, var Max var. Parabolic SAR, Por Welles Wilder A SAR corre acima ou abaixo da curva de preços, dependendo da tendência atual cada cruzamento da curva de preços é acreditado para indicar uma mudança de tendência Parâmetros Passo incremento do fator de aceleração, normalmente 0 02, Valor mínimo do fator de aceleração mínimo, normalmente 0 02, Max Accelerati No valor máximo do fator, normalmente 0 2 SAR é uma função recursiva que depende da direção da vela de preço inicial para valores consistentes o período LookBack deve ser longo o suficiente para conter pelo menos um cruzamento de preços de cruzamento Usa os preços de ativos atuais A função cria internamente Uma série e, portanto, deve ser chamado em uma ordem fixa no script Código-fonte em indicadores c exemplo em Indicatortest c. ShannonGain vars Dados, int TimePeriod var. Expected taxa de ganho logarítmico da série de dados na faixa de cerca de -0 0005 O ganho É derivada da probabilidade de Shannon P 1 ganho médio RootMeanSquare ganho 2 que é a probabilidade de um aumento ou queda de uma série de dados de alta entropia no próximo período de barra Uma taxa de ganho positivo indica que a série é mais provável de subir, um negativo A taxa de ganho indica que é mais provável que caia O crossover zero poderia ser usado para um sinal de comércio Algoritmo por John Conover Fonte disponível em indicadores c. ShannonEntropy vars Data, int Lengt H, int PatternSize var. Entropia de padrões na série de dados, em bit pode ser usado para determinar a aleatoriedade dos dados PatternSize 2 8 determina o particionamento dos dados em padrões de até 8 bits Cada valor de dados é maior do que o O valor anterior, ou não é uma informação binária e constitui um bit do padrão Quanto mais aleatórios os padrões são distribuídos, maior é a entropia de Shannon Dados totalmente aleatórios tem uma entropia de Shannon idêntica ao tamanho do padrão Algoritmo explicado no relatório financeiro Hacker blog fonte disponível em indicadores c. SIROC vars Dados, int TimePeriod, int EMAPeriod var. Smoothed Taxa de Mudança S-RoC por Fred G Schutzman Difere do ROC ver acima em que se baseia na média móvel exponencial EMA dos Dados series Believed to indicate the strength of a trend by determining if the trend is accelerating or decelerating Formula Current EMA - Previous EMA Previous EMA x 100 Source code in indicators c. SMA vars Data, int TimeP eriod var. Simple Moving Average the mean of the data, i e the sum divided by the time period Use Moment when long time periods are required. Smooth vars Data, int CutoffPeriod var. Ehler s super-smoothing filter, a 2-pole Butterworth filter combined with a SMA that suppresses the Nyquist frequency Can be used as a low-lag universal filter for removing noise from price data The minimum length of the Data series is 2 The function internally creates series and thus must be called in a fixed order in the script Source available in indicators c. SMom vars Data, int TimePeriod, int CutoffPeriod var. Smoothed Momentum by John Ehlers indicates the long term trend direction TimePeriod is the momentum period, CutoffPeriod is a Butterworth filter constant for lowpass filtering the momentum Source code in indicators c. Spearman vars Data, int TimePeriod var. Spearman s rank correlation coefficient correlation between the original Data series and the same series sorted in ascending order within TimePerio d 1 256 Returns the similarity to a steadily rising series and can be used to determine trend intensity and turning points Range -1 1 lag TimePeriod 2 For usage and details, see Stocks Commodities magazine 2 2011 Source available in indicators c. StdDev vars Data, int TimePeriod var. Standard Deviation of the Data series in the time period, from the ta-lib Use the square root of the second Moment when high accuracy or long time periods are required. Stoch int FastKPeriod, int SlowKPeriod, int SlowKMAType, int SlowDPeriod, int SlowDMAType. Stochastic Oscillator unrelated to stochastics, but its inventor, George Lane, looked for a fancy name Measures where the Close price is in relation to the recent trading range Formula FastK 100 Close-LL HH-LL SlowK MA FastK SlowD MA SlowK Uses the current asset price series and does not support TimeFrame Result in rSlowK rSlowD Some traders believe that the SlowK crossing above SlowD is a buy signal others believe they should buy when SlowD is below 20 and sell when it is above 80 Parameters FastKPeriod - Time period for the HH and LL to generate the FastK value, usually 14 SlowKPeriod - Time period for smoothing FastK to generate rSlowK usually 3 SlowKMAType - Type of Moving Average for Slow-K, usually MATypeEMA SlowDPeriod - Time period for smoothing rSlowK to generate rSlowD usually 3 SlowDMAType - Type of Moving Average for Slow-D, usually MATypeEMA. StochEhlers vars Data, int TimePeriod, int CutOffLow, int CutOffHigh var. Predictive stochastic oscillator by John Ehlers Measures where the Data value is in relation to its range within TimePeriod The data runs through a 2-pole highpass filter with period CutOffHigh and through a Butterworth lowpass filter with period CutOffLow Indicator algorithm explained in Ehler s Predictive Indicators paper usage example in the Ehlers script Source code in indicators c The function internally creates series and thus must be called in a fixed order in the script. StochF int FastKPeriod, int FastD Period, int FastDMAType var. Stochastic Fast Measures where the Close price is in relation to the recent trading range Formula Fast-K 100 Close-LL HH-LL Fast-D MA Fast-K Uses the current asset price series Does not support TimeFrame Result in rFastK rFastD Returns FastK Parameters FastKPeriod Time period for the HH and LL of Fast-K, usually 14 , FastDPeriod Moving Average Period for Fast-D usually 3 , FastDMAType Type of Moving Average for Fast-D, usually MATypeEMA. StochRSI vars Data, int TimePeriod, int FastKPeriod, int FastDPeriod, int FastDMAType var. Stochastic Relative Strength Index RSI Result in rFastK rFastD Returns FastK Parameters FastKPeriod Time period for building the Fast-K line , FastDPeriod Smoothing for making the Fast-D line Usually set to 3 , FastDMAType Type of Moving Average for Fast-D. Sum vars Data, int TimePeriod var. Sum of all Data elements in the time period. T3 vars Data, int TimePeriod, var VFactor var. An extremely smoothed Moving Average by Tim Tillson Uses a weighted sum of multiple EMAs Parameters VFactor Volume Factor, normally 0 7.TEMA vars Data, int TimePeriod var. Triple Exponential Moving Average by Patrick Mulloy, calculated from 3xEMA - 3xEMA of EMA EMA of EMA of EMA. Trima vars Data, int TimePeriod var. Triangular Moving Average also known under the name TMA a form of Weighted Moving Average where the weights are assigned in a triangular pattern F i the weights for a 7 period Triangular Moving Average would be 1, 2, 3, 4, 3, 2, 1 This gives more weight to the middle of the time series It causes better smoothing, but greater lag. Trix vars Data, int TimePeriod var.1-day Rate-Of-Change see ROC of a Triple EMA see TEMA. TrueRange var. True Range TR max High 0,Close 1 - min Low 0,Close 1 of the current asset price series See also ATR ATR S. TSF vars Data, int TimePeriod var. Time Series Forecast Returns b m TimePeriod i e the Linear Regression forecast for the next bar. TSI vars Data, int TimePeriod var. Trend Strength Index, an indicator by Frank Hassler who believed that it identifies trend strength A high TSI value above.1 65 indicates that short-term trend continuation is more likely than short-term trend reversal The function internally creates series and thus must be called in a fixed order in the script. TypPrice var. Typical Price Simply High Low Close 3 Uses the current asset price series. UltOsc int TimePeriod1, int TimePeriod2, int TimePeriod3 var. Ultimate Oscillator Parameters TimePeriod1 Number of bars for 1st period , TimePeriod2 Number of bars for 2nd period , TimePeriod3 Number of bars for 3rd period Uses the current asset price series Does not support TimeFrame. UO vars Data, int CutOff var. Universal oscillator by John Ehlers, from S C Magazine 1 2015 Removes white noise from the data, smoothes it and runs it through the AGC filter Detects trend reversals very early Output in the -1 1 range Source code in indicators c The function internally creates series and thus must be called in a fixed order in the scrip t. Variance vars Data, int TimePeriod var. Variance of the Data series in the time period, from the ta-lib Use Moment when high accuracy or long time periods are required. Volatility vars Data, int TimePeriod var. Annualized volatility of the Data series standard deviation of the log returns, multiplied with the square root of time frames in a year This is the standard measure of volatility used for financial models, such as the Black-Scholes model The function internally creates series and thus must be called in a fixed order in the script Source code in indicators c. VolatilityC int TimePeriod, int EMAPeriod var. Chaikin Volatility indicator by Marc Chaikin measures volatility in percent as momentum of the smoothed difference between High and Low An increase in the Chaikin Volatility indicates that a bottom is approaching, a decrease indicates that a top is approaching TimePeriod is the period of the momentum normally 10 , EMAPeriod determines the smoothing also, normally 10 Uses the curr ent asset price series The function internally creates series and thus must be called in a fixed order in the script Source code in indicators c. VolatilityMM vars Data, int TimePeriod, int EMAPeriod var. Min Max volatility of the Data series the difference of MaxVal and MinVal in the time period, smoothed by an EMA set EMAPeriod 0 for not smoothing The function internally creates a series when EMAPeriod 0 and then must be called in a fixed order in the script Source available in indicators c For the volatility of price candles, use ATR or ATRS. VolatilityOV int Days var. Annualized volatility of the current asset, calculated over the given number of Days usually 20 Empirical formula used by some options software packages OptionsVue for estimating the values of options, alternatively to Volatility Source code in options c which must be included for using this indicator. WCLPrice var. Weighted Close Price Uses the current asset price series. WillR int TimePeriod var. Williams Percent Range Form ula -100 HH-Close HH-LL Uses the current asset price series Does not support TimeFrame. WMA vars Data, int TimePeriod var. Linear Weighted Moving Average the weight of every bar decreases linearly with its age. ZigZag vars Data, var Depth, int Length, int Color var. ZigZag indicator converts the Data series into alternating straight trend lines with at least the given Depth and Length Non-predictive can only identify trends in hindsight Returned rSlope the slope of the last identified trend line upwards trends have a positive slope, downwards trends a negative slope rPeak the bar offset of the last identified peak rSign 1 if the last peak was a top, -1 if the last peak was a bottom rLength the number of bars of the last trend line ending with rPeak If a nonzero Color is given, the trend lines are plotted in the chart Source code in indicators c example in Indicatortest c The function internally creates series and thus must be called in a fixed order in the script. ZMA vars Data, int Time Period var. Zero-lag Moving Average by John Ehlers smoothes the Data series with an Exponential Moving Average EMA and applies an error correction term for compensating the lag The function internally creates a series and thus must be called in a fixed order in the script Source in indicators c. Standard parameters. The number of bars for the time period of the function, if any or 0 for using a default period. A data series often directly derived from the price functions price , priceClose etc Alternatively a user created series or any other double float array with the given minimum length can be used If not mentioned otherwise, the minimum length of the Data series is TimePeriod Some functions require a second data array Data2.Price data series can be explicitly given for some indicators, for using price series generated from a different asset or with a different TimeFrame Otherwise the prices of the current asset with a time frame equivalent to the bar period are used. Price variation or percentage, dependent on the function, for the current bar. Usage example. MACD Price,12,26,9 calculates the standard MACD for the given Price series The results are stored in the global variables rMACD rMACDSignal and rMACDHistory. The TA-Lib function prototypes are defined in include ta h Information about the usage and the indicator algorithms can be found online at The C source code of all included TA-Lib indicators is contained in and can be studied for examining the algorithms Some TA-Lib indicators that originally didn t work properly - such as Correlation or SAR - have been replaced by working versions The lite-C source code of most additional indicators that are not part the the TA-Lib is contained in include indicators c. All TA functions are applied on series and do normally not accept other data arrays In the INITRUN all TA functions return 0 and LookBack is automatically increased to the largest required lookback time by a TA function. Recursive TA functions - f i EMA or ATR - need a higher lookback period than their TimePeriod parameter see UnstablePeriod LookBack can be exceeded when TA functions are later called with a series offset or a different TimePeriod this will generate an Error 046 message Make sure that LookBack is always higher than the maximum TimePeriod plus the UnstablePeriod plus the highest possible offset of all used series. Some functions return more than one value, f i MACD The returned results are stored in global variables beginning with r they can be accessed after the function is called. Some functions only require a single Data value Rather than creating a Data series of length 1 simply a pointer to the Data value can be used Example var Raw MyIndicator var Transformed AGC Raw,0.TimeFrame affects subsequent data series and thus also affects all indicators that use the data series as input The TimePeriod is then not in Bar units, but in time frame units TimeFrame has no effect on indicators that do not use data series. Indicators tha t rely on the standard deviation f i Bollinger Bands become inaccurate when the standard deviation is below 0 0001, as it is then assumed to be zero by the TA-Lib This can happen on very short bar periods when the price does almost not move. For writing your own indicators, have a look at the examples inside indicators c But please do not modify indicators c - write the indicators in your own script, or in a dedicated script that you can then include in your strategies If you need a complex indicator that you can not be easily add, please ask for it on the Zorro user forum. It says a lot about your ethics that you did not feel the need to acknowledge the original coder of this AFL However, this particular implementation of ALMA in amibroker is not quite accurate The correct accurate implementation of ALMA in conformance with Ninja Trader and Meta Trader releases by the original developers of ALMA i e Arnaud Legoux has been submitted by me so that amibroker users can also benefit. just one word, this is fantastic. ALMA can be coded using the FIR function By accident I bumped into this writing. which does not seem to pop up when you look in the manual FIR allows you to do a convolution of an input array with a some smaller function like a Gaussian window type function resulting code. windowSize Param Window Size ,9,5,201,2 sigma Param Sigma ,6,1,20 Offset Param Offset ,0 85,0 05,1 0,0 05.function ALMAAFL input, range, Offset, sigma local m, im, s,Coeff m floor Offset range-1 s range sigma. SetChartOptions 0, chartShowDates Plot C, Close, colorLightGrey, styleCandle Plot rr,,colorBlue,1.in fact it can be programmed using. ws Param Window Size ,9,5,201,2 sigma Param Sigma , 6, 1, 20,1 Offset Param Offset ,0 85,0,1 0,0 05 bi BarIndex. m floor Offset ws-1 s ws sigma window IIf bi ws, Cum 1 -1 - m,0 window IIf bi ws, exp - window 2 2 s 2 ,0 rr FIR C, window, ws. SetChartOptions 0, chartShowDates Plot C, Close, colorLightGrey, styleCandle Plot rr, ALMA, colorBlue,1.Req afl cpoding for a special moving average ALMA. Req afl cpoding for a special moving average ALMA. Here is a special moving average It is based on probability distribution-gaussian. please read the pdf and try to code it if possible. The code has something special why so Why is ALMA SO SPECIAL LISTEN TO ITS DEVELOPERArnaud L In attempt to create a new kind of Moving Average with some friends colleagues because i was a little bit tired of the classical set of MA everybody s use for the last 10 years , we ve created this new one ALMA. It removes small price fluctuations and enhances the trend by applying a moving average twice, one from left to right and one from right to left At the end of this process the phase shift price lag commonly associated with moving averages is significantly reduced Zero-phase digital filtering reduces noise in the signal Conventional filtering reduces noise in the signal, but addS delay. The ALMA can give some excellent results if you take the time to tweak the parameters don t need to explain this part, it will be easy for you to find the right setting in less than hour. Arnaud L it is this application of moving average from left to right and from right to left is what makes it special - so far no such code exists in amibroker For those interested in mt4 code of alma, you can refer to attachment. It can be prepared from adheer pai based afl probability and gaussian distribution already existing Here is the Amibroker code for probability and gaussian distribution We need only the GUASSIAN PART. In this some removal and additions are needed to be done. removal Remove probabilityDENSITY ADDITION add sigma value of 6, add offset of 0 85 I request the experts to handle this task tHE ABOVE CODE BASIS WAS BY ADHEER to his solid content. Name Probability Density Gaussian Distribution Description Visual representation of distribution of the data-series e g Price, Price Change, LogNormal Price Change etc Identify whether the series exhibits normal Gaussian distribution Author Adheer Pai adheer at gmail dot com History 1 0 Original Release - July 08, 2009. The input series for plotting the Probability Density and Gaussian Distribution Use the array SERIES or replace accordingly. Constants PI 3 14159 SHOWBELLCURVE Show HIDEBELLCURVE Hide. AFL Inputs nSample Param DataSet Size , 500, 100, 1000 nSegments Param Density Segments , 15, 10, 20 bGauss ParamList Gaussian Curve , SHOWBELLCURVE HIDEBELLCURVE, 0 nPrecision Param Precision Digits , 5, 0, 6 nPrecision 8 nPrecision 10. Constants - system and derived nBarIndex SelectedValue BarIndex nFirstValidBar -1 for i 0 i BarCount i if IsEmpty SERIES i nFirstValidBar i break nSample Max Min nBarIndex - nFirstValidBar nSample ,1. DataSize 0 Number of samples it should be same as nPeriod arrMean MA SERIES, nSample arrMax HHV SERIES, nSample arrMin LLV SERIES, nSample arrSDev StDev SERIES, nSample. currMax arrMax nBarIndex Maximum of the range currMin arrMin nBarIndex Minimum of the range Mu arrMean nBarIndex Mean Mu Sigma arrSDev nBarIndex Standard Deviation of the Range Sigma. rangeOfBar currMax-currMin nSegments The range of each distribution bar barFrequency 0 Occurances within each bar MaxFrequency 0 Highest number of occurrances. DisplayBorder Displays the charting borders function DisplayBorder GfxSelectPen colorBrown, 1, styleDashed GfxMoveTo pxMargin, pxMargin GfxLineTo pxMargin, pxHeight - pxMargin GfxLineTo pxWidth - pxMargin, pxHeight - pxMargin GfxLineTo pxWidth - pxMargin, pxMargin GfxLineTo pxMargin, pxMargin. computeSigmaBandDistribution Computes the distribution withing the specified sigma band bounded by minvalue and maxvalue function computeSigmaBandDistribution MinValue, MaxValue nCount 0 for i nBarIndex i nBarIndex - nSample i 0 i-- if SERIES i MinValue SERIES i MaxValue nCount return 100 nCount nSample. getGaussianValue Function to compute the Gaussian distribution value Y for a given value of X non-scaled function getGaussianValue inputValue Steps to compute normal Gaussian distribution 1 Compute x - mu squared, multiply it by -1 step1 -1 inputValue - Mu 2 2 Compute twice of sigma squared step2 2 Sigma Sigma 3 Divide 1 by 2, and get the exp step3 exp step1 step2 4 Now, divide step 3 by sigma step4 step3 Sigma 5 Now, divide step 4 by square-root of 2 x PI step5 step4 sqrt 2 PI. Compute the arithmetic mean, minimum and maximum of the price series Compute the frequency of occurrances for nIndex nBarIndex nIndex nBarIndex - nSample nIndex 0 nIndex -- nCurrIndex int SERIES nIndex - currMin rangeOfBar nCurrIndex Max Min nSegments-1, nCurrIndex ,0 barFrequency nCurrIndex MaxFrequency Max MaxFrequency, barFrequency nCurrIndex. Now display the frequency of occurrances - aka distribution GfxSetBkMode 1 GfxSelectFont Verdana , 8, 800 GfxSetTextAlign 6 GfxSetTextColor colorRed pxScaleX pxWidth - 2 pxMargin nSegments pxScaleY 0 9 pxHeight - 2 pxMargin MaxFrequency for i 0 i nSegments i pxStartX pxMargin i pxScaleX pxEndX pxStartX pxScaleX pxStartY pxMargin barFrequency i pxScaleY GfxGradientRect pxStartX, pxHeight - pxStartY pxEndX, pxHeight - pxMargin, ColorRGB 70,255,255 , ColorRGB 70,20,255 GfxTextOut NumToStr 100 barFrequency i nSample 4 2 , pxStartX pxScaleX 2 , pxHeight - pxStartY - 15. Now plot the mean and the standard-deviation bars range pxScaleXPixelsPerPriceUnit pxWidth - 2 pxMargin currMax - currMin. meanLineX pxMargin Mu - currMin pxScaleXPixelsPerPriceUnit GfxSelectPen colorBlue, 2, 3 GfxMoveTo meanLineX, pxMargin GfxLineTo meanLineX, pxHeight - pxMargin GfxTextOut Mean , meanLineX, pxHeight - pxMargin GfxTextOut NumToStr Mu, nPrecision , meanLineX, pxHeight - pxMargin 3 for i 1 i 6 i N ow plot the Mean - 1-StDev sDevBand pxMargin Mu i Sigma - currMin pxScaleXPixelsPerPriceUnit if sDevBand pxWidth - pxMargin GfxSelectPen ColorRGB 128,128,128 , 1, 4 GfxMoveTo sDevBand pxMargin GfxLineTo sDevBand pxHeight - pxMargin GfxTextOut NumToStr i,1 0 SD , sDevBand, pxHeight - pxMargin GfxTextOut NumToStr Mu i sigma, nPrecision , sDevBand, pxHeight - pxMargin 3 sDevBand pxMargin Mu - i Sigma - currMin pxScaleXPixelsPerPriceUnit if sDevBand pxMargin GfxSelectPen ColorRGB 128,128,128 , 1, 4 GfxMoveTo sDevBand pxMargin GfxLineTo sDevBand pxHeight - pxMargin GfxTextOut - NumToStr i,1 0 SD , sDevBand, pxHeight - pxMargin GfxTextOut NumToStr Mu - i sigma, nPrecision , sDevBand, pxHeight - pxMargin 3. Legend and data information GfxSetBkMode 1 GfxSetTextAlign 0 24 GfxSelectFont Verdana , 8, 400 GfxSetTextColor colorBlue GfxTextOut Latest NumToStr SERIES nBarIndex , nPrecision , pxMargin 10, pxMargin 15 GfxTextOut Mean NumToStr Mu, nPrecision , pxMargin 10, pxMargin 30 GfxTe xtOut Sigma NumToStr Sigma, nPrecision , pxMargin 10, pxMargin 45. Now display the distribution of the first 10 standard deviations or less nLastPixelY pxMargin 60 for numOfStDevs 1 numOfStDevs 10 numOfStDevs nCount computeSigmaBandDistribution Mu - numOfStDevs Sigma, Mu numOfStDevs Sigma GfxTextOut NumToStr numOfStDevs, 1 0 - Sigma NumToStr nCount,5 2 , pxMargin 10, nLastPixelY nLastPixelY nLastPixelY 15 if nCount 100 numOfStDevs 100.currLineX pxMargin SERIES nBarIndex - currMin pxScaleXPixelsPerPriceUnit GfxSelectPen colorGreen, 2, 3 GfxMoveTo currLineX pxMargin GfxLineTo currLineX pxHeight - pxMargin GfxSetTextAlign 6 GfxSetTextColor colorGreen GfxTextOut Latest , CurrLineX, pxMargin 2. Display the Gaussian Distribution if requested by the user if bGauss SHOWBELLCURVE Now display the normal distribution curve based on sigma and mu graphStepX CurrMax - Mu Max 100, pxWidth-2 pxMargin if graphStepX 0 GaussianMaxima 0 for x CurrMin x CurrMax x x graphStepX GaussianMaxima Max GaussianMaxima, getGaussianValue x. pxGaussianScaleY 0 9 pxHeight - 2 pxMargin GaussianMaxima GfxSelectPen colorOrange, 2, 0 for x CurrMin x CurrMax x x graphStepX gaussianValue getGaussianValue x pxPointX x - CurrMin pxScaleXPixelsPerPriceUnit pxMargin pxPointY pxHeight - gaussianValue - 0 pxGaussianScaleY - pxMargin if x CurrMin GfxMoveTo pxPointX, pxPointY GfxLineTo pxPointX, pxPointY. property copyright Copyright 2010, TrendLaboratory property link ---- indicator settings property indicatorchartwindow property indicatorbuffers 3 property indicatorcolor1 Yellow property indicatorcolor2 LightBlue property indicatorcolor3 Tomato property indicatorwidth1 2 property indicatorwidth2 2 property indicatorwidth3 2 ---- indicator parameters extern int Price 0 Price Mode 0 6 extern int WindowSize 9 Window Size extern double Sigma 6 0 Sigma parameter extern double Offset 0 85 Offset of Gaussian distribution 0 1 extern double PctFilter 0 Dynamic filter in decimal extern int Shift 0 extern int ColorMode 0 0-on,1-off extern int ColorBarBack 1 extern int AlertMode 0 Sound Alert switch 0-off,1-on extern int WarningMode 0 Sound Warning switch 0-off,1-on ---- indicator buffers double ALMA double Uptrend double Dntrend double trend double Del. int drawbegin bool UpTrendAlert false, DownTrendAlert false double wALMA ------------------------------------------------------------------ Custom indicator initialization function ------------------------------------------------------------------ int init ---- indicator buffers mapping IndicatorBuffers 5 SetIndexBuffer 0,ALMA SetIndexBuffer 1,Uptrend SetIndexBuffer 2,Dntrend SetIndexBuffer 3,trend SetIndexBuffer 4,Del ---- drawing settings SetIndexStyle 0,DRAWLINE SetIndexStyle 1,DRAWLINE SetIndexStyle 2,DRAWLINE drawbegin WindowSize SetIndexDrawBegin 0,drawbegin SetIndexDrawBegin 1,drawbegin SetIndexDrawBegin 2,drawbegin SetIndexShift 0,Shift SetIndexShift 1,Shift SetIndexShift 2,Shift IndicatorDigits MarketInfo Symbol, MODEDIGITS 1 ---- name for DataWindow and indicator subwindow label IndicatorShortName ALMA WindowSize SetIndexLabel 0, ALMA SetIndexLabel 1, ALMA Uptrend SetIndexLabel 2, ALMA Dntrend. double m MathFloor Offset WindowSize - 1 double s WindowSize Sigma. ArrayResize wALMA, WindowSize double wsum 0 for int i 0i WindowSizei wALMA i MathExp - i-m i-m 2 s s wsum wALMA i. for i 0i WindowSizei wALMA i wALMA i wsum. if shift Bars - WindowSize continue. double sum 0 double wsum 0.for i 0i WindowSizei if i WindowSize sum wALMA i iMA NULL,0,1,0,0,Price, shift WindowSize - 1 - i. if wsum 0 ALMA shift sum. if PctFilter 0 Del shift MathAbs ALMA shift - ALMA shift 1.double sumdel 0 for int j 0j WindowSize-1j sumdel sumdel Del shift j double AvgDel sumdel WindowSize. double sumpow 0 for j 0j WindowSize-1j sumpow MathPow Del j shift - AvgDel,2 double StdDev MathSqrt sumpow WindowSize. double Filter PctFilter StdDev. if MathAbs ALMA shift - ALMA shift 1 Filter ALMA shift ALMA shift 1 else Filter 0.if ColorMode 0 trend shift trend shift 1 if ALMA shift - ALMA shift 1 Filter trend shift 1 if ALMA shift 1 - ALMA shift Filter trend shift -1.if trend shift 0 Uptrend shift ALMA shift if trend shift ColorBarBack 0 Uptrend shift ColorBarBack ALMA shift ColorBarBack Dntrend shift EMPTYVALUE if WarningMode 0 trend shift 1 0 i 0 PlaySound else if trend shift 0 Dntrend shift ALMA shift if trend shift ColorBarBack 0 Dntrend shift ColorBarBack ALMA shift ColorBarBack Uptrend shift EMPTYVALUE if WarningMode 0 trend shift 1 0 i 0 PlaySound ---------- string Message. if trend 2 0 trend 1 0 Volume 0 1 UpTrendAlert Message Symbol M Period HMA Signal for BUY if AlertMode 0 Alert Message UpTrendAlert true DownTrendAlert false. if trend 2 0 trend 1 0 Volume 0 1 DownTrendAlert Message Symbol M Period HMA Signal for SELL if AlertMode 0 Alert Message DownTrendAlert true UpTrendAlert false. The mt4 code is poosted to provide some kind of hint for coding in afl. looking forawrd to alma code in afl here on traderji as it doesnt exist anywhere else as of now regards ford.

No comments:

Post a Comment