Friday 20 April 2018

Sistema de origem comercial


Os sistemas Z.


Os sistemas Z são estratégias de portfólio pré-fabricadas, prontas para execução, baseadas em vários algoritmos publicados em trabalhos de pesquisa financeira, no Black Book ou no Financial Hacker. Para evitar mal-entendidos: eles não devem ser a única razão de usar o Zorro! Recomendamos que você aprenda a desenvolver seus próprios sistemas. O desenvolvimento da estratégia não é totalmente trivial - mas, se fosse, haveria muitos mais sistemas de trabalho, mais pessoas iriam trocá-los e as ineficiências do mercado que eles estão explorando serão lançadas mais cedo ou mais tarde. Este efeito mantém o número de estratégias bem-sucedidas sob controle e fornece codificadores qualificados uma grande vantagem sobre os comerciantes analfabetos de código.


Ao usar um sistema Z, não faça isso cegamente, mas aprenda o desenvolvimento do sistema, entenda como ele funciona e eventualmente o substitua por seu próprio sistema. Existem cinco boas razões pelas quais você deveria usar seus próprios sistemas. Primeiro, você tem a chance de programar melhores estratégias do que os sistemas Z relativamente simples. Em segundo lugar, os próprios sistemas cabem exatamente suas idéias comerciais e seus limites de capital e de risco. Em terceiro lugar, você pode enfrentar reduções com maior confiança, pois você sabe exatamente o que os sistemas fazem e por quê. Em quarto lugar, você adquirirá experiência em programação e estatística, importante para o sucesso a longo prazo, não só com negociação algorítmica. E, finalmente, você não pode culpar-nos por perdas.


Os sistemas Z usam algoritmos relativamente simples, mas todos foram submetidos a um processo sólido de desenvolvimento e teste, com os métodos descritos no Livro Negro. As primeiras versões dos sistemas estavam em negociação ao vivo desde 2018; Os resultados até agora foram consistentes com a simulação. Observamos constantemente os sistemas e substituímos algoritmos expirados ou sistemas inteiros quando pensamos que eles não são rentáveis. Os sistemas atuais cobrem uma grande variedade de métodos de comércio, taxas de ganhos e orçamentos:


Silver, Index CFDs.


EUR, USD, GBP, JPY.


Os sistemas Z não começarão imediatamente. Com exceção dos Z8 e Z9 que baixam automaticamente os preços da Internet, você precisa obter dados históricos para testá-los. Então, quando você pede ajuda no fórum do usuário porque o & quot; Z1 mostra muitos erros de "histórico faltando", sabemos que você não leu o manual! Para comercializar os sistemas Z ao vivo, você provavelmente também precisará mudar o nome de alguns ativos, dependendo do nome que seu corretor use; Procure por detalhes em Dicas e Truques abaixo. Não é necessário treinar os sistemas Z. Nós fornecemos novas regras e parâmetros treinados com qualquer atualização Zorro.


Para o investimento a longo prazo, os sistemas Z8 ou Z9 são os mais adequados, uma vez que possuem a maior taxa de ganhos e o menor risco. Os outros sistemas podem causar uma perda completa do capital investido. Muitos têm longos períodos de retirada como você pode ver na tabela acima. Então, é mais provável que você comece em uma redução do que não. Esteja preparado para perdas e não investir o que você não pode perder.


Ao clicar em [Test], o sistema é testado para determinar o seu desempenho com diferentes configurações de slides e parâmetros e diferentes contas de corretores. Para manter o tamanho da instalação do Zorro pequeno, os arquivos de dados históricos exigidos não estão incluídos no arquivo de configuração. Obtenha-os separadamente na página de download do Zorro. Os sistemas Z normalmente precisam de dados de preços históricos de 2018, Z7 a partir de 2004. Os resultados dos testes podem variar ligeiramente dos números acima. As contas de corretores com maiores montantes de lote, margens e comissões podem até produzir resultados muito diferentes.


Os números de desempenho e as curvas de equidade nesta página são de uma análise progressiva em uma conta de microlote FXCM simulada com alavanca de 100: 1, com todos os controles deslizantes em suas posições padrão. Z8 e Z9 são simulados com uma conta IB Regt Margem na alavanca 2: 1. Todos os sistemas não diários foram treinados com sobreamostragem e, portanto, são robustos contra o ruído da curva de preços.


As estratégias Z não estão disponíveis no script. Eles são executáveis ​​compilados (*.x) apenas. Isso não é devido a algum algoritmo de comércio secreto - os algoritmos são publicados, então qualquer usuário do Zorro pode verificá-los e escrever estratégias similares. Mas se fornecemos o código do script, qualquer pessoa pode ver quando as estratégias compram e quando eles vendem. Em seguida, seria fácil presa dos usuários do sistema Z com métodos avançados. Pelo mesmo motivo, algumas das estratégias contêm um elemento aleatório que dificulta a previsão de seu comportamento comercial. Este elemento aleatório tem apenas um pequeno efeito sobre o desempenho da estratégia, mas garante que muitas pessoas possam trocar as estratégias sem prejudicar-se. É tecnicamente quase impossível engenharia reversa das estratégias Zorro compiladas para determinar seu comportamento comercial.


Devido ao limite de lucro, a licença Zorro gratuita permite trocar apenas um sistema - qualquer uma das estratégias Z ou um sistema próprio - em uma conta de dinheiro real. Z1, Z2 e Z8 estão incluídos na versão Zorro gratuita. Os outros sistemas estão incluídos como versões de demonstração; As versões para negociação de dinheiro real estão incluídas no Zorro S.


Os sistemas Z não reinventam automaticamente os lucros. O volume negociado pode ser controlado manualmente com o controle deslizante Capital (veja abaixo) e não está relacionado ao saldo da conta. Os fatores OptimalF são usados ​​por alguns sistemas para distribuir o capital entre os componentes, mas não para reinvestir. Se você quiser reinvestir seus lucros, use o controle deslizante Capital para aumentar o investimento proporcionalmente à raiz quadrada do lucro acumulado até agora.


Z1 comercializa um portfólio de algoritmos seguindo tendências com moedas, commodities e índices. Os algoritmos são variantes dos sistemas do capítulo 3 do Livro Negro. Eles são auto-adaptados ao mercado dentro de certos limites e podem detectar períodos de mercado não lucrativos. Os fatores OptimalF são usados ​​para distribuir o capital entre os componentes. As saídas de comércio são tratadas por TMFs. Alguns dos algoritmos controlam a duração do comércio movendo a perda de parada; Isso pode fazer com que a parada se mova em ambas as direções.


A curva de equidade acima está no lado otimista devido ao viés de seleção gerando os fatores OptimalF de todo o período de simulação. Para reduzir o risco de expiração de componentes únicos, um mecanismo de negociação de curva de patrimônio é implementado. Você pode desativá-lo com a bandeira Phantom (veja abaixo). Uma tabela com os estados atuais do algoritmo é exibida na página de status comercial:


Na matriz acima, os algoritmos ativos são exibidos com seu identificador (VO, LP, etc.) e L e / ou S para a direção comercial preferida atualmente, longa, curta ou ambas. Os algoritmos que estão atualmente ganhando são exibidos em um retângulo verde. Algoritmos que atualmente estão perdidos e, portanto, temporariamente suspensos (se a negociação da curva de equidade estiver ativada, veja abaixo) são exibidos em um retângulo vermelho. Os números exibidos são o total de ganhos ou perdas por componente, incluindo transações fantasmas.


Devido ao seu período de lookback relativamente longo, Z1 e Z2 só devem ser negociados com corretores que fornecem um histórico de preços suficiente. Se os intervalos de dados de preços forem indicados na janela de mensagens no início, é recomendável usar o sinalizador de pré-carga (veja abaixo) ou trocar o sistema com um corretor diferente. Caso contrário, o histórico de preços reduzidos pode afetar o desempenho nas primeiras semanas.


Z2 é um portfólio de variantes dos sistemas de reversão média do capítulo 4 do Livro Negro. Enquanto seus próprios algoritmos são mais ou menos correlacionados, ele é anticorrelacionado com Z1. Os algoritmos são auto-adaptados ao mercado. Os fatores OptimalF são usados ​​para distribuir o capital entre os componentes. As saídas de comércio são tratadas por TMFs. Alguns dos algoritmos controlam a duração do comércio movendo a perda de parada; Isso pode fazer com que a parada se mova em ambas as direções.


Como Z1, Z2 só deve ser negociado com corretores que fornecem um histórico de preços suficiente.


Uma combinação de Z1 e Z2, explorando a anticorrelação de suas curvas de equidade. Ao combinar Z1 e Z2 com um sistema composto, o lucro é aumentado e as reduções são reduzidas. O lucro Z12 excede a soma dos lucros Z1 e Z2, enquanto o requisito de capital é menor que a soma de ambos. As observações acima sobre a redução de Z1 / Z2, negociação de curva de equidade e período de lookback também se aplicam a Z12.


O Z3 é um sistema de comércio de commodities e índice de médio prazo. Ele detecta clusters de preços que precedem as fugas. Os breakouts de preços ocorrem com frequência especialmente com metais e índices de estoque, e constituem uma ineficiência explorável. Os resultados não estão correlacionados com Z1 e Z2, então todos os sistemas podem ser comercializados simultaneamente com Zorro S. Como o Z3 é baseado em um único algoritmo, a curva de equidade não é afetada pelo viés de seleção.


O desempenho do Z3 depende da volatilidade dos ativos. Em períodos de baixa volatilidade, a equidade é mais ou menos plana. Tal como acontece com Z1 e Z2, a duração do comércio é controlada movendo o nível de parada de perdas. Isso pode fazer com que a parada se mova em ambas as direções e para apertar mesmo quando o comércio não é lucrativo.


Z7 é um sistema de negociação forex baseado em um algoritmo de detecção de padrões de preços semelhante ao capítulo 5 do Livro Negro (uma variante é descrita no blog do Financial Hacker). É projetado para requisitos de capital baixos e trades curtos (5 horas). As negociações são desencadeadas por padrões de preços que precedem as lacunas do fim de semana e os movimentos de curta duração ou para baixo. O Z7 usa padrões diferentes para as sessões dos EUA, da Europa e do Pacífico. Os resultados não estão relacionados a tendências e ciclos, e não correlacionados com os outros sistemas.


Todos os negócios da Z7 terminam após pelo menos um dia de mercado, a maioria depois de algumas horas. A perda de parada é relativamente distante e é usada apenas para limitação de risco. Um mecanismo de arranque bloqueia lucros quando o comércio corre bem em situações de alta volatilidade.


O Z8 é um sistema de negociação de longo prazo com base em um algoritmo de otimização de média / variância de Markowitz (MVO) modificado. É uma versão melhorada do sistema MVO descrito no Financial Hacker. O Z8 abre uma carteira de ETFs, ações ou outros ativos determinados por uma lista de ativos externos e reatribui o capital investido entre os componentes da carteira a cada 5 semanas para alcançar uma curva de saldo positiva com variação mínima. Uma vez que negocia com baixa alavancagem, o lucro, mas também o risco é menor em comparação com os outros sistemas.


A curva de saldo acima é de um teste de amostra externa com os ativos padrão, com base em uma conta de margem com alavanca 2: 1 e margem inicial de $ 5000. O backtest reinvestir o crescimento do capital para o poder de 0,9, e mantém o lucro remanescente como reserva de caixa na conta para amortização das cobranças. Os ativos, alavancagem de conta e fonte de dados de preço devem ser configurados em uma lista de ativos chamada AssetsZ8.csv. Por padrão, ele contém um conjunto de ETFs que foram selecionados pela diversidade da indústria e por suas supostas perspectivas a longo prazo. O Z8 também pode negociar carteiras de ações ou qualquer outro instrumento com retornos positivos a longo prazo. Forex ou CFDs não são adequados para Z8. Para adicionar um novo recurso, basta duplicar uma linha em AssetsZ8.csv e editar o nome do recurso na primeira coluna. Para desativar temporariamente uma linha, adicione um '#' na frente do nome do recurso. A coluna Símbolo contém também a fonte do download. Entre 10 e 300 ativos podem ser contidos na lista. Quando você remove um recurso da lista, certifique-se de fechar manualmente qualquer uma das suas posições abertas (isso não acontecerá automaticamente).


O Z8 não precisa ser treinado, uma vez que este é processado automaticamente pelo processo MVO. O botão [Train] pode ser usado para encontrar recursos com baixa correlação (apenas Zorro S). Ele exibe um heatmap das correlações entre os ativos em Assets8.csv (vermelho = alta correlação, azul = baixa correlação). Se você não tem Zorro S, você pode usar o script para gerar mapas de calor no Financial Hacker.


Para o backtest, os dados históricos são baixados automaticamente dos provedores de dados configurados na coluna 'Símbolo' na lista de ativos, portanto, não são necessários mais arquivos de histórico de preços. Se você quiser baixar dados de uma fonte diferente, edite a lista de ativos ou carregue-o antes de iniciar a estratégia. O sistema detectará automaticamente que os dados atualizados já estão presentes e não tentam fazer o download novamente.


Para negociar Z8, a API do corretor deve suportar o comando GET_POSITION, que é o caso da API IB TWS. Certifique-se de que você assinou dados de mercado para todos os ativos negociados (com IB, normalmente o "Pacote de Valor dos EUA"), que você tem permissão para trocar esses itens (verifique todas as caixas relevantes na página "Permissões de comércio" e "Questões comerciais") e que a alavancagem no AssetsZ8.csv corresponde à alavancagem da sua conta. Se o seu portfólio contiver ETFs alavancados, verifique seu requisito de margem: o IB aceita a Alavancagem 2 para ETF desalavancados ou 2x alavancados; Alavancar 1.333 para ETFs 3x; e alavanca 1 para 4x ETFs.


Uma vez que a Z8 comercializa apenas a cada 5ª semana, não precisa ser executada permanentemente e não requer nenhum VPS e nenhuma conexão intermediária permanente. Basta iniciá-lo no modo [Comércio] uma vez a cada 5 semanas após o horário de abertura do mercado de Nova York (9:30 ET). O Z8 descarregará primeiro os preços históricos de todos os ativos e, em seguida, calculará o portfólio ótimo. Defina o controle deslizante Capital na margem total que deseja investir. Após cerca de um minuto, uma caixa de mensagem aparecerá, assim:


& quot; Old? é a posição atual no recurso e "novo" é a nova posição. Ao clicar em [Sim] venderá ou comprará automaticamente a diferença de qualquer posição, e assim otimizará o portfólio. Se a API do corretor não suportar solicitações de posição, as posições "antigas" serão todas 0, mesmo quando as posições estão abertas. Nesse caso, abra ou feche as diferenças de posição manualmente na plataforma de negociação do corretor, e clique em [Não] na caixa de mensagem. Depois, a sessão de negociação é fechada e a data sugerida para o próximo início é impressa na janela de mensagem.


Uma vez que você só pode comprar números inteiros de ações, a margem real será normalmente menor do que o Capital, dependendo dos pesos e dos preços dos componentes da carteira. O capital máximo pode ser configurado em Z. ini (veja abaixo); está limitado a US $ 7000 com a versão gratuita do Zorro. Para evitar chamadas de margem, recomendamos configurar o Capital não superior a cerca de 80% do patrimônio da conta. Para nenhuma alavancagem, configure Capital em 50%. Se o sistema não abrir todas as negociações - por exemplo, devido a um problema de conexão temporária ou a estar fora do mercado - basta executá-lo novamente. Como ele detecta as posições reais, executá-lo várias vezes não faz mal. Se você perdeu a data de início sugerida, talvez porque está de férias com todo o dinheiro que você fez até agora, execute na próxima ocasião. Faltar uma única data não causa muito mal, mas não perca muitas datas seguidas.


Z9 é um sistema de negociação de longo prazo semelhante ao Z8, mas com base no "Dual Momentum & quot; estratégia de Gary Antonacci (ver livros). Ele rota uma seleção de ativos no AssetsZ9.csv, que deve conter uma mistura de setores dos EUA, índices não-americanos e títulos ou tesouraria. O portfólio é girado de modo que ele sempre contém o 1/3 superior dos ativos, selecionados pelo maior momento relativo e momento absoluto positivo. Se nenhum setor ou índice tiver qualquer impulso positivo, o sistema investe completamente em títulos. Se o tanque de ligações também, o sistema permanece fora do mercado.


A curva de saldo acima é de um teste de amostra externa com os ativos padrão, com base em uma conta de margem com alavanca 2: 1 e capital inicial de $ 5000. Embora o sistema Z9 use um algoritmo matematicamente mais simples do que o sistema Z8 acima, mostra melhor CAGR. Editando a lista de ativos, configurando os parâmetros z. ini, reinvestir lucro e reequilibrar os trabalhos do portfólio, conforme descrito para o Z8 acima. Na coluna Tipo da lista AssetsZ9, digite 0 para setores, 1 para títulos, 2 para índices não norte-americanos e 3 para um índice principal que representa o mercado norte-americano. O índice principal é usado para detectar falhas no mercado e pode ser omitido com risco ligeiramente maior. Tal como acontece com Z8, [Train] gera um mapa de calor de correlação. Para negociar Z8 e Z9 simultaneamente na mesma conta, o AssetsZ8 e AssetsZ9 devem ser modificados para garantir que eles não compartilhem ativos.


Configuração e negociação.


Toda estratégia Z pode ser configurada na inicialização com parâmetros de um arquivo. ini e é controlada em tempo de execução com os controles deslizantes Capital e Panic. Primeiro configure a estratégia para o seu país e outros requisitos: abra Strategy \ Z. ini com o editor do script e edite os seguintes parâmetros:


O arquivo. ini é lido no início da estratégia. Se você deseja trocar diferentes estratégias Z com diferentes parâmetros, salve o Z. ini sob o nome da estratégia, f. i. Strategy \ Z4.ini para Z4. A estratégia irá então ler os parâmetros de seu arquivo. ini correspondente. Em tempo de execução, as estratégias Z são controladas com dois controles deslizantes:


O mais importante é o controle deslizante Capital. Antes de negociar o sistema, certifique-se de ter lido esta página de cima para baixo. Determine o seu requisito de capital mínimo, testando as estratégias com diferentes configurações do controle deslizante e verifique o capital necessário no relatório de desempenho. Coloque o capital suficiente para negociação, seja na sua conta do corretor ou, pelo menos, na sua conta bancária. Para reinvestir seus lucros, você pode aumentar lentamente o controle deslizante quando o capital da conta crescer. Para não arriscar uma chamada de margem, tome cuidado para reinvestir ou retirar o capital somente de acordo com a regra da raiz quadrada explicada no Livro Negro.


Para um backtest realista, verifique se as configurações da conta na lista de ativos estão corretas e atualizadas. Por padrão, uma conta média FXCM micro com alavancagem de 100: 1 e tamanho de lote de 1000 contratos é simulada no backtest. Para o Z8, é uma conta de margem IB comum com alavanca 2: 1. O requisito de capital e o desempenho do sistema podem ser drasticamente diferentes em outras contas, especialmente com alavancagem maior ou menor. Se um determinado recurso não for fornecido pelo seu corretor, remova-o da estratégia conforme descrito abaixo. Se estiver disponível, mas sob um símbolo diferente, edite a lista de ativos e insira seu nome de símbolo. Os cidadãos dos EUA normalmente não estão autorizados a negociar CFDs; nesse caso, defina a bandeira FXOnly (veja abaixo) para negociar somente Forex.


Verifique os requisitos do seu corretor e conta. Problemas típicos não são capazes de abrir ou fechar um comércio (& quot; Não é possível fechar. & Quot;) devido a conformidade NFA, conformidade FIFO, um símbolo incorreto, um tamanho de comércio inválido ou fechamento parcial não suportado. Verifique se NFA e Hedge estão configurados corretamente.


Antes de começar ao vivo, execute um backtest com o controle deslizante Capital na mesma posição que na sessão de negociação. Isso permite que o sistema compare permanentemente o desempenho ao vivo com o desempenho do backtest, usando o Índice de Sangue Frio. O Capital pode ser aumentado mais tarde, mas a posição inicial deve corresponder ao último teste. O CBI é impresso uma vez por dia na janela de mensagem e na página de status. Considere puxar para fora quando chegar a um valor baixo ou 0.


Depois de iniciar uma estratégia, as primeiras negociações serão inseridas após aproximadamente 1..3 dias. A frequência dos negócios depende da estratégia e do mercado; Em períodos não lucrativos com alta eficiência no mercado, haverá apenas alguns negócios, especialmente quando o Phantom estiver configurado no arquivo Z. ini. A maioria das negociações é suspensa por 2-3 dias, mas algumas podem permanecer abertas por semanas, quando são lucrativas.


O saldo da sua conta geralmente diminuirá nas primeiras semanas após o início de uma estratégia. Esta não é uma redução real, mas o resultado de dois efeitos estatísticos. Negociações não lucrativas são fechadas cedo, enquanto os negócios lucrativos permanecem abertos por mais tempo e, assim, contribuem mais tarde para o saldo. Além disso, as flutuações da equidade - as ondulações de cima e para baixo 'na curva de equidade - quase sempre excederão o lucro inicial, a menos que você tenha um início excepcionalmente afortunado. Ambos os efeitos causarão períodos de saldo e equidade negativos na primeira vez de quase todas as estratégias. Você pode ver um começo tão típico na curva de lucro abaixo. Quando o lucro se acumula, os períodos de saldo negativos ficam mais curtos e eventualmente desaparecem. No entanto, se você ainda não está na zona de lucro após vários meses e seus retornos comerciais ainda se desviam em grande parte do desempenho previsto, como visível de um CBI baixo, algo está errado. A estratégia pode ter expirado e você deve parar de negociar.


Curva de lucro ao vivo típica de um sistema de negociação automatizado (Zorro Z5, agora expirado). Observe as flutuações da equidade e os picos negativos. Durante a vida, o sistema foi altamente lucrativo e ganhou. Ainda assim, as pessoas perderam dinheiro com ele, entrando em um topo de equidade e puxando o pânico no final da próxima retirada. Desde o início demorou cerca de 8 semanas até que o lucro acumulado tenha sido acumulado para manter a curva patrimonial com segurança acima de zero. Outros sistemas Z têm flutuações de capital ainda maiores e períodos de redução mais longos.


Eventos - como entrar e sair de negócios, ou arrastar a perda de parada - são exibidos na janela de mensagem do Zorro. As estratégias usam funções de gerenciamento de comércio e adaptam permanentemente os limites de parada ao desenvolvimento de preços do ativo. Além das mensagens padrão (ver Negociação), Z1, Z2 e Z12 informam de tempos em tempos quando o risco ou o lucro possível das negociações abertas mudam. Eles são exibidos dessa maneira na janela de mensagem do Zorro:


[AUD / USD: CY: S4400] Risco estimado: 150.


[USD / JPY: CT: S4321] Lucro estimado: 720.


O risco estimado é a perda máxima, o lucro estimado é a vitória mínima que o Zorro atualmente prevê para o comércio, em unidades da moeda da sua conta. Quando o risco diminui ou o lucro aumenta, a posição está se movendo em direção favorável. Note que é apenas uma estimativa, de modo que a perda real e a vitória real podem ser pior.


Z Systems Tips & amp; Truques.


Parando & amp; Começando: no início da negociação, os sistemas baixam dados de preços recentes do corretor ou de outras fontes de preços para preencher o período LookBack. Portanto, evite iniciar as estratégias durante o fim de semana quando os preços recentes não estão disponíveis e os servidores intermediários podem estar offline. Caso contrário, as lacunas nos dados de preços podem causar um desempenho reduzido durante a semana seguinte. Uma vez que um sistema está sendo comercializado, pare apenas em caso de emergência. A maioria dos sistemas não entra em negociações imediatamente após a inicialização, de modo que a parada e o início freqüentes farão com que um sistema não seja comercializado. Enquanto um sistema é parado, não pode reagir no mercado, o que corre o perigo de uma perda potencial quando as posições ainda estão abertas.


Testando & amp; Re-treinamento: as estratégias podem ser testadas com dados de preços históricos (você pode obter os dados de preços da página de download do Zorro). O significado dos parâmetros de desempenho pode ser encontrado no relatório de desempenho. Os parâmetros mais recentes são usados ​​para negociação. As estratégias devem ser re-treinadas regularmente para mantê-las lucrativas; Em testes anteriores fora da amostra, eles começaram a deteriorar-se cerca de 4 ... 12 meses após o último treino. Novos conjuntos de parâmetros serão lançados com atualizações do Zorro, portanto, não é necessário treiná-los. Mas se você quiser, você pode fazer isso com o Zorro S clicando no botão [Trem], mesmo quando estiver ao vivo. O arquivo de fatores (Z12.fac) de Z12 não é re-treinado, pois muda muito devagar e precisa do período completo de simulação. Um novo arquivo de fatores é fornecido com qualquer atualização Zorro.


Invest & amp; Retirar: todas as estratégias rentáveis ​​têm longas retiradas que estão listadas na tabela acima (pior destruição). Tome cuidado para recuperar sua conta quando você estiver em uma redução e seu patrimônio fica perigosamente baixo. Por outro lado, se você não tem o Zorro S, remova os lucros regularmente da sua conta - a versão gratuita do Zorro irá parar de negociar quando seu saldo exceder 7000 $ ou o equivalente na sua moeda da conta (veja o limite do lucro). Para o montante máximo para reinvestir ou para retirar durante uma sessão de negociação, siga a regra de raiz quadrada. As exceções são Z8 e Z9, onde o requisito de capital é determinado principalmente por margem e não por redução.


Capital baixo: você pode negociar estratégias com baixo capital, como algumas centenas de dólares, quando você move o controle deslizante Capital principalmente para a esquerda e executa testes repetidos até que o valor exibido em Capital atenda suas necessidades. Você também pode reduzir o requisito de capital removendo ativos da carteira, conforme descrito abaixo. Note-se que o baixo capital e poucos ativos reduzirão normalmente o desempenho ao vivo e aumentarão o risco e as cobranças devido ao número reduzido de negócios.


Excluir ativos: para excluir todos os ativos, exceto as moedas, defina FXOnly (veja acima). Para excluir ativos específicos, use a lista Excluir em z. ini. Para excluir um determinado componente da negociação em Z1, Z2 ou Z12, edite o arquivo de fatores Z12.fac (Data \ Z12.fac) e coloque sinais negativos '-' na frente de seus fatores OptimalF. Os algoritmos com os identificadores de ES, HU, LP, LS, VO pertencem a Z1, A2, BB, CT, CY, HP a Z2. Um exemplo para excluir o algoritmo CT com o recurso USD / CAD:


Os componentes com um fator OptimalF negativo ou .000 são automaticamente excluídos desta forma. Esteja ciente de que excluir os ativos ou algoritmos menos rentáveis ​​gerará um resultado de backtest muito otimista devido ao viés de seleção.


Renomear recursos: Edite a lista de ativos - normalmente Histórico \ AssetsFix. csv - e insira o nome do recurso usado pelo corretor na coluna Símbolo da planilha, conforme descrito na lista de ativos. Não modifique os nomes dos ativos na primeira coluna, pois eles são usados ​​pelas estratégias. As exceções são Z8 e Z9, para as quais você pode adicionar ou remover livremente ativos na lista de ativos.


Múltiplos Zorros: você precisará do Zorro S para comercializar vários sistemas Z ao mesmo tempo. Certifique-se também com seu corretor que sua conta está configurada para permitir várias sessões. Alguns corretores configuram contas para sessões únicas somente por padrão. Uma vez que o Zorro armazena seus logs e trades em arquivos com o nome do script, não troque o mesmo script com vários Zorros em paralelo, exceto quando você deu os nomes diferentes dos scripts ou os está executando de diferentes pastas de instalação do Zorro.


Imposto: na maioria dos países você tem que pagar impostos por lucros comerciais. Normalmente, o corretor mantém registros de seus negócios que você pode baixar de seu site. Caso contrário, o Zorro também registra todas as negociações na planilha trades. csv na pasta de dados para sua declaração de imposto. Juros (rollover) e lucro / perda são registrados separadamente. Normalmente, você deve enviar esta planilha ou os registros do corretor junto com sua declaração de imposto.


Atualizando: publicaremos atualizações nas estratégias Z em intervalos regulares, por isso recomendamos visitar o fórum do usuário ou o site Zorro de vez em quando. Se você marcou a caixa no formulário de download, você também será informado por e-mail sobre as atualizações. Por favor, veja aqui como mudar de uma versão antiga para uma nova, sem interrupção na negociação.


Vencimento: todas as estratégias eventualmente podem expirar; por exemplo, o sistema Z5 expirou quando o suíço removeu o limite de CHF. Se suspeitarmos que um determinado sistema expire, anunciaremos que no fórum e também informaremos os assinantes e usuários do Zorro S por e-mail. Normalmente, nós forneceremos um sucessor depois que um sistema expirou. Enquanto os mercados não forem perfeitamente eficazes, sempre haverá possibilidades infinitas para algoritmos comerciais lucrativos.


Regras para receita regular com negociação automatizada.


Tem capital suficiente. O capital mínimo para uma renda regular modesta está no intervalo de US $ 20.000. A versão gratuita do Zorro limita o tamanho da sua conta a US $ 7000 (veja restrições), mas você não precisa de todo o seu capital na conta do corretor - você pode mantê-lo em uma conta bancária e se recuperar quando seu patrimônio cai perigosamente baixo. Ter pelo menos o dobro do capital exigido do relatório de desempenho à sua disposição. A maioria dos corretores apoiam fundos de depósito rápido por cartão de crédito em alguns minutos.


Quanto dinheiro é "muito"? A maneira mais simples é comparar a perda com o capital exigido - quando você perde mais, você excedeu a redução normalizada e deve parar. Uma estimativa mais precisa é a seguinte fórmula: E = C + P * t / y - D * sqrt ((t + l) / y). E é o capital mínimo esperado, C é o seu capital inicial (= o Capital Necessário da simulação), P é o lucro do teste, t é o tempo de negociação, y o período de teste, D a retirada do teste e l o comprimento da retirada. A melhor maneira é verificar o índice de sangue frio do seu sistema atualizado diariamente pelos sistemas Z e impresso na página de status e no log.


Pelo mesmo motivo, muitas vezes não interrompem e reencaminham estratégias: isso encerra negociações abertas, inicializa qualquer parâmetro intermediário que a estratégia possa usar, ajusta o período de lookback e, portanto, reduz ou reduz o desempenho dependente da estratégia. Qualquer fechamento manual de negócios pode custar várias centenas de pips e pode converter uma estratégia vencedora em uma perda - não importa se essas negociações estavam na zona de lucro ou não. Para uma "suspensão suave" de uma estratégia sem perda, defina a margem como zero, de modo que nenhuma nova negociação seja aberta, e espere até que a própria estratégia tenha fechado todas as negociações abertas.


Os sistemas Z.


Os sistemas Z são estratégias de portfólio pré-fabricadas, prontas para execução, baseadas em vários algoritmos publicados em trabalhos de pesquisa financeira, no Black Book ou no Financial Hacker. Para evitar mal-entendidos: eles não devem ser a única razão de usar o Zorro! Recomendamos que você aprenda a desenvolver seus próprios sistemas. O desenvolvimento da estratégia não é totalmente trivial - mas, se fosse, haveria muitos mais sistemas de trabalho, mais pessoas iriam trocá-los e as ineficiências do mercado que eles estão explorando serão lançadas mais cedo ou mais tarde. Este efeito mantém o número de estratégias bem-sucedidas sob controle e fornece codificadores qualificados uma grande vantagem sobre os comerciantes analfabetos de código.


Ao usar um sistema Z, não faça isso cegamente, mas aprenda o desenvolvimento do sistema, entenda como ele funciona e eventualmente o substitua por seu próprio sistema. Existem cinco boas razões pelas quais você deveria usar seus próprios sistemas. Primeiro, você tem a chance de programar melhores estratégias do que os sistemas Z relativamente simples. Em segundo lugar, os próprios sistemas cabem exatamente suas idéias comerciais e seus limites de capital e de risco. Em terceiro lugar, você pode enfrentar reduções com maior confiança, pois você sabe exatamente o que os sistemas fazem e por quê. Em quarto lugar, você adquirirá experiência em programação e estatística, importante para o sucesso a longo prazo, não só com negociação algorítmica. E, finalmente, você não pode culpar-nos por perdas.


Os sistemas Z usam algoritmos relativamente simples, mas todos foram submetidos a um processo sólido de desenvolvimento e teste, com os métodos descritos no Livro Negro. As primeiras versões dos sistemas estavam em negociação ao vivo desde 2018; Os resultados até agora foram consistentes com a simulação. Observamos constantemente os sistemas e substituímos algoritmos expirados ou sistemas inteiros quando pensamos que eles não são rentáveis. Os sistemas atuais cobrem uma grande variedade de métodos de comércio, taxas de ganhos e orçamentos:


Silver, Index CFDs.


EUR, USD, GBP, JPY.


Os sistemas Z não começarão imediatamente. Com exceção dos Z8 e Z9 que baixam automaticamente os preços da Internet, você precisa obter dados históricos para testá-los. Então, quando você pede ajuda no fórum do usuário porque o & quot; Z1 mostra muitos erros de "histórico faltando", sabemos que você não leu o manual! Para comercializar os sistemas Z ao vivo, você provavelmente também precisará mudar o nome de alguns ativos, dependendo do nome que seu corretor use; Procure por detalhes em Dicas e Truques abaixo. Training the Z systems is not required. We provide new trained rules and parameters with any Zorro update.


For long-term investment, the Z8 or Z9 systems are the best suited since they have the highest win rate and the smallest risk. The other systems can cause a complete loss of the invested capital . Many have long drawdown periods as you can see in the table above. So you're more likely to start in a drawdown than not. Be prepared for losses and do not invest what you can't afford to lose.


By clicking [ Test ], the system is tested for determining its performance with different slider and parameter settings and different broker accounts. For keeping the Zorro installation size small, the required historical price data files are not included in the setup file. Get them separately on the Zorro download page. The Z systems normally need historical price data from 2018, Z7 from 2004. Your test results can slightly differ from the figures above. Broker accounts with higher lot amounts, margins, and commissions can even produce very different results.


The performance figures and equity curves on this page are from a walk-forward analysis on a simulated FXCM microlot account at 100:1 leverage, with all sliders at their default positions. Z8 and Z9 are simulated with an IB RegT Margin account at 2:1 leverage. All non-daily systems have been trained with oversampling and are thus robust against price curve noise.


The Z strategies are not available in script. They are compiled executables ( *.x ) only. This is not due to some secret trade algorithm - the algorithms are published, so any Zorro user can check them out and write similar strategies. But if we provided the script code, anyone could see when the strategies buy and when they sell. It would then be easy to prey on Z system users with fore-running methods. For the same reason, some of the strategies contain a random element that makes it hard to predict their trading behavior. This random element has only a small effect on the strategy performance, but it ensures that many people can trade the strategies without hampering each other. It is technically almost impossible to reverse engineer compiled Zorro strategies for determining their trading behavior.


Due to the profit limit, the free Zorro license allows to trade only one system - either one of the Z strategies or a system of your own - on a real money account. Z1, Z2, and Z8 are included in the free Zorro version. The other systems are included as demo versions; the versions for real money trading are included in Zorro S.


The Z systems do not automatically reinvest profits. The traded volume can be manually controlled with the Capital slider (see below) and is unrelated to the account balance. OptimalF factors are used by some systems for distributing the capital among the components, but not for reinvesting. If you want to reinvest your profits, use the Capital slider for increasing the investment proportionally to the square root of the profit accumulated so far.


Z1 trades a portfolio of trend following algorithms with currencies, commodities, and indices. The algorithms are variants of the systems from chapter 3 of the Black Book. They are self-adapting to the market within certain boundaries, and can detect unprofitable market periods. OptimalF factors are used for distributing the capital among the components. Trade exits are handled by TMFs. Some of the algorithms control the trade duration by moving the stop loss; this can cause the stop to move in both directions.


The equity curve above is on the optimistic side due to selection bias from generating the OptimalF factors from the whole simulation period. For reducing the expiration risk of single components, an equity curve trading mechanism is implemented. You can deactivate it with the Phantom flag (see below). A table with the current algorithm states is displayed on the trade status page:


In the above matrix, active algorithms are displayed with their identifier ( VO , LP , etc.) and L and/or S for the currently preferred trade direction, long, short, or both. Algorithms that are currently winning are displayed on a green rectangle. Algorithms that are currently losing and thus temporarily suspended (if equity curve trading was enabled, see below) are displayed on a red rectangle. The displayed numbers are the total win or loss per component, including phantom trades.


Due to their relatively long lookback period, Z1 and Z2 should only be traded with brokers that provide sufficient price history. If price data gaps are indicated in the message window at start, it is recommended to use the Preload flag (see below) or trade the system with a different broker. Otherwise the shortened price history can affect the performance in the first weeks.


Z2 is a portfolio of variants of the mean reversion systems from chapter 4 of the Black Book. While its own algorithms are more or less correlated, it is anticorrelated to Z1. The algorithms are self-adapting to the market. OptimalF factors are used for distributing the capital among the components. Trade exits are handled by TMFs. Some of the algorithms control the trade duration by moving the stop loss; this can cause the stop to move in both directions.


Like Z1, Z2 should only be traded with brokers that provide sufficient price history.


A combination of Z1 and Z2, exploiting the anticorrelation of their equity curves. By combining Z1 and Z2 to a compound system, profit is increased and drawdowns are reduced. The Z12 profit exceeds the sum of Z1 and Z2 profits, while the capital requirement is lower than the sum of both. The above remarks about the Z1/Z2 drawdown, equity curve trading, and lookback period also apply to Z12.


Z3 is a medium-term commodity and index trading system. It detects price clusters that precede breakouts. Price breakouts happen frequently especially with metals and stock indices, and constitute an exploitable inefficiency. The results are uncorrelated to Z1 and Z2, so all systems can be traded simultaneously with Zorro S. Since Z3 is based on a single algorithm, the equity curve is unaffected by selection bias.


The Z3 performance depends on the asset volatility. In low volatility periods the equity is more or less flat. As with Z1 and Z2, the trade duration is controlled by moving the stop loss level. This can cause the stop to move in both directions and to tighten even when the trade is not in profit.


Z7 is a forex trading system based on a price pattern detection algorithm similar to chapter 5 of the Black Book (a variant is described on the Financial Hacker blog). It is designed for low capital requirement and short trades (5 hours). Trades are triggered by price patterns preceding weekend gaps and shortlived up - or downwards movements. Z7 uses different patterns for the US, European, and Pacific sessions. The results are unrelated to trends and cycles, and uncorrelated to the other systems.


All Z7 trades end after at least one market day, most after a few hours. The stop loss is relatively distant and is used for risk limitation only. A trailing mechanism locks profits when the trade goes well in high volatility situations.


Z8 is a long-term trading system based on a modified Markowitz mean/variance optimization (MVO) algorithm. It is an improved version of the MVO system described on Financial Hacker. Z8 opens a portfolio of ETFs, stocks, or other assets determined by an external asset list, and re-allocates the invested capital among the portfolio components every 5 weeks for achieving a positive balance curve with minimum variance. Since it trades with low leverage, the profit, but also the risk is smaller compared to the other systems.


The balance curve above is from an out-ouf-sample test with the default assets, based on a margin account with 2:1 leverage and $5000 start margin. The backtest reinvests the capital growth to the power of 0.9, and keeps the remaining profit as cash reserve on the account for buffering drawdowns. The assets, account leverage, and price data source must be set up in an asset list named AssetsZ8.csv . By default it contains a set of ETFs that were selected by industry diversity and by their supposed long-term prospects. Z8 can also trade stock portfolios or any other instruments with long-term positive returns. Forex or CFDs are not suited for Z8. For adding a new asset, just duplicate a line in AssetsZ8.csv and edit the asset name in the first column. For temporarily out-commenting a line, add a '#' in front of the asset name. The Symbol column contains also the download source. Between 10 and 300 assets can be contained in the list. When you remove an asset from the list, make sure to also manually close any of its open positions (this won't happen automatically).


Z8 needs not be trained, since this is automatically handled by the MVO process. The [ Train ] button can instead be used for finding assets with low correlation (Zorro S only). It displays a heatmap of the correlations between the assets in Assets8.csv (red = high correlation, blue = low correlation). If you don't have Zorro S, you can use the script for generating heatmaps on Financial Hacker.


For the backtest, historical data is automatically downloaded from the data providers set up in the 'Symbol' column in the asset list, so no further price history files are necessary. If you want to download data from a different source, either edit the asset list, or load it before starting the strategy. The system will automatically detect that up-to-date data is already present, and not attempt to download it again.


For trading Z8, the broker API must support the GET_POSITION command, which is the case for the IB TWS API. Make sure that you've subscribed market data for all traded assets (with IB, normally the "US Value Bundle"), that you're permitted to trade them (check all relevant boxes on the "Trade Permissions" page), and that the leverage in AssetsZ8.csv matches your account leverage. If your portfolio contains leveraged ETFs, check their margin requirement: IB accepts Leverage 2 for unleveraged or 2x leveraged ETFs; Leverage 1.333 for 3x ETFs; and Leverage 1 for 4x ETFs.


Since Z8 trades only every 5th week, it needs not run permanently, and requires no VPS and no permanent broker connection. Just start it in [ Trade ] mode once every 5 weeks after the opening time of the New York market (9:30 ET). Z8 will first download historical prices of all assets, then calculate the optimal portfolio. Set the Capital slider to the total margin you want to invest. After about a minute a message box will pop up, like this:


"Old" is the current position in the asset, and "new" is the new position. Clicking [ Yes ] will automatically sell or buy the difference of any position, and this way optimize the portfolio. If the broker API does not support position requests, the 'old' positions will all be 0, even when positions are open. In that case open or close the position differences manually in the broker's trading platform, then click [ No ] on the message box. Afterwards the trading session is closed, and the suggested date for the next start is printed in the message window.


Since you can only buy integer numbers of shares, the real invested margin will normally be smaller than Capital , dependent on portfolio component weights and prices. The maximum capital can be set up in Z. ini (see below); it is limited to $7000 with the free Zorro version. For avoiding margin calls, we recommend to set Capital not higher than about 80% of the account equity. For no leverage, set Capital at 50%. If the system does not open all trades - for instance due to a temporary connection problem or to being outside market hours - just run it again. Since it is detects actual positions, running it several times does no harm. If you missed the suggested start date, maybe because you're on vacation with all the money you made so far, run it at the next occasion. Missing a single date does not do much harm, but don't miss many dates in a row.


Z9 is a long-term trading system similar to Z8, but based on the "Dual Momentum" strategy by Gary Antonacci (see books). It rotates a selection of assets in AssetsZ9.csv , which should contain a mix of US sectors, non-US indices, and bonds or treasury. The portfolio is rotated so that it always contains the top 1/3 of the assets, selected by their highest relative momentum and positive absolute momentum. If no sector or index has any positive momentum, the system invests completely in bonds. If bonds tank too, the system stays out of the market.


The balance curve above is from an out-ouf-sample test with the default assets, based on a margin account with 2:1 leverage and $5000 start capital. Although the Z9 system uses a mathematically simpler algorithm than the Z8 system above, is shows better CAGR. Editing the asset list, setting up the z. ini parameters, reinvesting profit, and rebalancing the portfolio works just as described for Z8 above. In the Type column of the AssetsZ9 list, enter 0 for sectors, 1 for bonds, 2 for non-US indexes, and 3 for a lead index that represents the US market. The lead index is used for detecting market crashes and can be omitted at slightly higher risk. As with Z8, [ Train ] generates a correlation heatmap. For trading Z8 and Z9 simultaneously on the same account, AssetsZ8 and AssetsZ9 must be modified for making sure that they share no assets.


Setup and trading.


Every Z strategy can be configured at startup with parameters from an. ini file, and is controlled at runtime with the Capital and Panic sliders. First set up the strategy to your country and other requirements: open Strategy\Z. ini with the script editor, and edit the following parameters:


The. ini file is read at start of the strategy. If you want to trade different Z strategies with different parameters, save Z. ini under the name of the strategy, f. i. Strategy\Z4.ini for Z4. The strategy will then read the parameters from its corresponding. ini file. At runtime, the Z strategies are controlled with two sliders:


The most important is the Capital slider. Before trading the system, make sure you've read this page from top to bottom. Determine your minimum capital requirement by testing the strategies with different settings of the slider, and check the required capital in the performance report. Set aside enough capital for trading, either in your broker account or at least in your bank account. For reinvesting your profits, you can slowly increase the slider when the capital on the account grows. For not risking a margin call, take care to re-invest or withdraw capital only according to the square root rule explained in the Black Book.


For a realistic backtest, make sure that the account settings in the asset list are correct and up to date. By default, an average FXCM micro account with 100:1 leverage and 1000 contracts lot size is simulated in the backtest. For Z8 it's an average IB Margin account with 2:1 leverage. The capital requirement and the system performance can be drastically different on other accounts, especially with higher or lower leverage. If a certain asset is not provided by your broker, remove it from the strategy as described below. If it is available, but under a different symbol, edit the asset list and enter its symbol name. US citizens are normally not allowed to trade CFDs; in that case set the FXOnly flag (see below) for trading Forex only.


Check the requirements of your broker and account. Typical issues are not being able to open or to close a trade ( "Can't close. " ) due to NFA compliance, FIFO compliance, a wrong symbol, an invalid trade size, or unsupported partial closing. Make sure that NFA and Hedge are set correctly.


Before starting live, run a backtest with the Capital slider at the same position as in the trading session. This allows the system to permanently compare live performance with backtest performance, using the Cold Blood Index. The Capital can be increased later, but the initial position must match the last backtest. The CBI is printed once per day in the message window and on the status page. Consider pulling out when it gets down to a low value or 0.


After starting a strategy, the first trades will be entered after about 1..3 days. The frequency of trades depends on the strategy and the market; in unprofitable periods with high market efficiency there will be only a few trades, especially when Phantom is set in the Z. ini file. Most trades are hold for 2-3 days, but some can stay open for weeks when they are profitable.


Your account balance will often go down in the first weeks after starting a strategy. This is not a real drawdown, but the result of two statistical effects. Unprofitable trades are closed early, while profitable trades stay open longer and thus contribute later to the balance. Additionally, the equity fluctuations - the up and down 'ripples' in the equity curve - will almost always exceed the initial profit unless you have an exceptionally lucky start. Both effects will cause periods of negative balance and equity in the first time of almost all strategies. You can see such a typical start in the profit curve below. When the profit accumulates, negative balance periods get shorter and eventually disappear. However if you're not yet in the profit zone after several months and your trade returns still deviate largely from the predicted performance, as visible from a low CBI , something is wrong. The strategy might be expired and you should stop trading it.


Typical live profit curve of an automated trading system (Zorro Z5, now expired). Note the equity fluctuations and the negative peaks. During its lifetime the system was highly profitable and steadily winning. Still, people lost money with it by entering at an equity top and pulling out in panic at the bottom of the next drawdown. From the start it took about 8 weeks until enough profit was accumulated for keeping the equity curve safely above zero. Other Z systems have even higher equity fluctuations and longer drawdown periods.


Events - such as entering and exiting trades, or trailing the stop loss - are displayed in Zorro's message window. The strategies use trade management functions and adapt the stop limits permanently to the price development of the asset. Additionally to the standard messages (see Trading), Z1, Z2, and Z12 inform from time to time when the risk or possible profit of open trades change. They are displayed this way in Zorro's message window:


[AUD/USD:CY:S4400] Estimated risk: 150.


[USD/JPY:CT:S4321] Estimated profit: 720.


The estimated risk is the maximum loss, the estimated profit is the minimum win that Zorro currently predicts for the trade, in units of your account currency. When the risk goes down or the profit goes up, the position is moving in favourable direction. Note that it's only an estimate, so the real loss as well as the real win can be worse.


Z Systems Tips & Truques.


Stopping & Starting: At trading start, the systems download recent price data from the broker or from other price sources for filling the LookBack period. Therefore avoid starting the strategies during the weekend when recent prices are not available and broker servers can be offline. Otherwise gaps in the price data can cause reduced performance during the following week. Once a system is trading, stop it only in case of an emergency. Most systems do not enter trades immediately after being started, so frequent stopping and starting will cause a system not to trade. While a system is stopped, it can not react on the market, which bears the danger of a potential loss when positions are still open.


Testando & amp; Re-Training: The strategies can be tested with historical price data (you can get the price data from the Zorro download page). The meaning of the performance parameters can be found under performance report. The most recent parameters are used for trading. The strategies must be re-trained regularly for keeping them profitable; in out-of-sample backtests they started to deteriorate about 4..12 months after the last training. New parameter sets will be released with Zorro updates, so dou don't need to train them yourself. But if you want, you can do that with Zorro S by clicking the [ Train ] button, even while live trading. The factors file ( Z12.fac ) of Z12 is not re-trained since it changes very slowly and needs the full simulation period. A new factors file is provided with any Zorro update.


Invest & amp; Withdraw: All profitable strategies have long drawdowns that are listed in the table above ( Worst Drawdown ). Take care to remargin your account when you're in a drawdown and your equity gets dangerously low. On the other hand, if you don't have Zorro S, remove profits regularly from your account - the free Zorro version will stop trading when your balance exceeds 7000 $ or the equivalent in your account currency (see profit ceiling). For the maximum amount to reinvest or to withdraw during a trading session, follow the square root rule. Exceptions are Z8 and Z9 where capital requirement is mainly determined by margin, not by drawdown.


Low Capital: You can trade strategies with low capital, such as a few hundred dollars, when you move the Capital slider mostly to the left and run repeated tests until the value displayed under Capital meets your needs. You can also reduce the capital requirement by removing assets from the portfolio, as described below. Note that low capital and few assets will normally reduce the live performance and increase risk and drawdowns due to the reduced number of trades.


Exclude Assets: For excluding all assets except currencies, set FXOnly (see above). For excluding particular assets, use the Exclude list in z. ini . For excluding a certain component from trading in Z1, Z2, or Z12, edit the Z12.fac factors file ( Data\Z12.fac ) and place minus signs ' - ' in front of its OptimalF factors. The algorithms with the ES , HU , LP , LS , VO identifiers belong to Z1, A2 , BB , CT , CY , HP to Z2. An example for excluding the CT algorithm with the USD/CAD asset:


Components with a negative or .000 OptimalF factor are automatically excluded this way. Be aware that excluding the least profitable assets or algorithms will generate a too optimistic backtest result due to selection bias.


Rename assets: Edit the asset list - normally History\AssetsFix. csv - and enter the asset name used by the broker in the Symbol column of the spreadsheet, as described under asset list. Do not modify the asset names in the first column, since they are used by the strategies. Exceptions are Z8 and Z9 , for which you can freely add or remove assets in the asset list.


Multiple Zorros: You'll need Zorro S for trading several Z systems at the same time. Also make sure with your broker that your account is set up to allow multiple sessions. Some brokers set up accounts for single sessions only by default. Since Zorro stores its logs and trades in files named after the script, do not trade the same script with several Zorros in parallel, except when you gave the scripts different names, or are running them from different Zorro installation folders.


Tax: In most countries you have to pay tax for trading profits. Normally the broker keeps records of your trades that you can download from his website. Otherwise Zorro also records all trades in the trades. csv spreadsheet in the Data folder for your tax declaration. Interest (rollover) and profit/loss are recorded separately. Usually you have to submit this spreadsheet or the broker's records together with your tax declaration.


Updating: We'll publish updates to the Z strategies in regular intervals, so it's recommended to visit the user forum or the Zorro website from time to time. If you checked the box on the download form, you'll also be informed by email about updates. Please look here for how to move from an old to a new version with no interruption to trading.


Expiration : All strategies can eventually expire; for instance the Z5 system expired when the Swiss removed the CHF cap. If we suspect that a certain system will expire, we'll announce that on the forum and will also inform subscribers and Zorro S users by email. Normally we'll provide a successor after a system expired. As long as the markets are not perfectly effective, there will always be infinite possibilities for profitable trade algorithms.


Rules for regular income with automated trading.


Have enough capital . The minimum capital for a modest regular income is in the $20,000 range. The free Zorro version limits your account size to $7000 (see restrictions), but you need not all your capital in the broker account - you can keep it in a bank account and remargin when your equity drops dangerously low. Have at least twice the required capital from the performance report at your disposal. Most brokers support fast depositing funds by credit card in a few minutes.


How much money is "too much"? The simplest way is comparing the loss with the required capital - when you lose more, you've exceeded the normalized drawdown and should stop. A more precise estimate is the following formula: E = C + P*t/y - D*sqrt((t+l)/y) . E is the expected minimum equity, C is your initial capital (= the Required Capital of the simulation), P is the test profit, t is the trade time, y the test period, D the test drawdown, and l the drawdown length. The best way is checking the Cold Blood Index of your system that's daily updated by the Z systems and printed on the status page and the log.


For the same reason, don't often stop and re-start strategies: this closes open trades, initializes any intermediate parameters the strategy might use, sets back the lookback period, and thus more or less reduces the performance dependent on the strategy. Any manual closing of trades can cost several hundred pips and can convert a winning strategy in a losing one - no matter if those trades were in the profit zone or not. For 'soft stopping' a strategy without loss, set the margin to zero so that no new trades are opened, then wait until the strategy itself has closed all open trades.


Sistemas de negociação: o que é um sistema de negociação?


Um sistema de negociação é simplesmente um grupo de regras específicas, ou parâmetros, que determinam pontos de entrada e saída para um determinado patrimônio. Esses pontos, conhecidos como sinais, são frequentemente marcados em um gráfico em tempo real e levam a execução imediata de um comércio.


Médias móveis (MA) Osciladores estocásticos Força relativa Bollinger Bands & reg; Muitas vezes, duas ou mais dessas formas de indicadores serão combinadas na criação de uma regra. Por exemplo, o sistema de crossover MA usa dois parâmetros de média móvel, a longo prazo e a curto prazo, para criar uma regra: "compre quando o curto prazo cruza acima do longo prazo e venda quando o contrário é verdadeiro". Em outros casos, uma regra usa apenas um indicador. Por exemplo, um sistema pode ter uma regra que proíbe qualquer compra, a menos que a força relativa esteja acima de um determinado nível. Mas é uma combinação de todos esses tipos de regras que fazem um sistema comercial.


Como o sucesso do sistema geral depende de quão bem as regras funcionam, os comerciantes do sistema gastam otimizar o tempo para gerenciar o risco, aumentar o valor obtido por comércio e alcançar estabilidade a longo prazo. Isso é feito modificando diferentes parâmetros dentro de cada regra. Por exemplo, para otimizar o sistema de crossover MA, um comerciante testaria para ver quais médias móveis (10 dias, 30 dias, etc.) funcionam melhor e, em seguida, implementá-los. Mas a otimização pode melhorar os resultados apenas por uma pequena margem - é a combinação de parâmetros utilizados que, em última instância, determinarão o sucesso de um sistema.


Isso tira toda a emoção das negociações - A emoção é muitas vezes citada como uma das maiores falhas de investidores individuais. Os investidores que são incapazes de lidar com as perdas adivinhem suas decisões e acabam perdendo dinheiro. Ao seguir rigorosamente um sistema pré-desenvolvido, os comerciantes do sistema podem renunciar à necessidade de tomar quaisquer decisões; Uma vez que o sistema é desenvolvido e estabelecido, o comércio não é empírico porque é automatizado. Ao reduzir as ineficiências humanas, os comerciantes do sistema podem aumentar os lucros.


Os sistemas de negociação são complexos - Esta é a sua maior desvantagem. Nos estágios de desenvolvimento, os sistemas de comércio exigem uma sólida compreensão da análise técnica, a capacidade de tomar decisões empíricas e um conhecimento profundo de como os parâmetros funcionam. Mas mesmo que você não esteja desenvolvendo seu próprio sistema comercial, é importante estar familiarizado com os parâmetros que compõem o que você está usando. Adquirir todas essas habilidades pode ser um desafio.


Mathematics in Trading: How to Estimate Trade Results.


Introduction: Mathematics is the Queen of the Sciences.


A certain level of mathematical background is required of any trader, and this statement needs no proof. The matter is only: How can we define this minimum required level? In growth of his or her trading experience, trader often widens his or her outlook "single-handed", reading posts on forums or various books. Some books require lower level of mathematical background of readers, some, on the contrary, inspire one to study or brush up one's knowledge in one field of pure sciences or another. We will try to give some estimates and their interpretations in this single article.


Of Two Evils Choose the Least.


There are more mathematicians in the world than successful traders. This fact is often used as an argument by those opposing complex calculations or methods in trading. We can say against it that trading is not only ability to develop trading rules (analyzing skills), but also ability to observe these rules (discipline). Besides, a theory that would exactly describe pricing on financial markets have not been yet created by now (I think it will never be created). The creation of the theory (discovery of mathematical nature) of financial markets itself would mean death of these markets which is an undecidable paradox, in terms of philosophy. However, if we face the question of whether to go to the market with not quite satisfactory mathematical description of the market or without any description at all, we choose the least evil: We choose methods of estimation of trading systems.


What is Abnormality of Normal Distribution?


One of basic notions in the theory of probability is the notion of normal (Gaussian) distribution. Why is it named like this? Many natural processes turned out to be normally distributed. To be more exact, the most natural processes, at the limit, reduce to normal distribution. Let us consider a simple example. Suppose we have a uniform distribution on the interval of 0 to 100. Uniform distribution means that probability of falling any value on the interval and probability of that 3. 14 (Pi) will fall is the same as that of falling 77 (my favorite number with two sevens). Modern computers help to generate a rather good pseudorandom-number sequence.


How can we obtain normal distribution of this uniform distribution? It turns out that, if we take every time several random numbers (for example, 5 numbers) of a unique distribution and find the mean value of these numbers (this is called 'to take a sample') and if the amount of such samples is great, the newly obtained distribution will tend to normal. The central limit theorem says that this relates to not only samples taken from unique distributions, but also to a very large class of other distributions. Since properties of normal distribution have been studied very well, it will be much easier to analyze processes if they are represented as a process with normal distribution. However, seeing is believing, so we can see the confirmation of this central limit theorem using a simple MQL4 indicator.


Let us launch this indicator on any chart with different N (amount of samples) values and see that the empirical frequency distribution becomes smoother and smoother.


Figura 1. Indicator that creates a normal distribution of a uniform one.


Here, N means how many times we took the average of pile=5 uniformly distributed numbers on the interval of 0 to 100. We obtained four charts, very similar in appearance. If we normalize them somehow at the limit (adjunct to a single scale), we will obtain a several realizations of the standard normal distribution. The only fly in this ointment is that pricing on financial markets (to be more exact, price increments and other derivatives of those increments), generally speaking, does not fit into the normal distribution. The probability of a rather rare event (for example, of price decreasing by 50%) on financial markets is, whereas low, but still considerably higher than at normal distribution. This is why one should remember this when estimating risks on the basis of normal distribution.


Quantity Transforms into Quality.


Even this simple example of modelling normal distribution shows that the amount of data to be processed counts for much. The more initial data there are, the more precise and valid the result is. The smallest number in the sample is considered to have to exceed 30. It means that, if we want to estimate results of trades (for example, an Expert Advisor in the Tester), the amount of trades below 30 is insufficient to make statistically reliable conclusions about some parameters of the system. The more trades we analyze, the less the probability is that these trades are just happily snatched elements of a not very reliable trading system. Hence, the final profit in a series of 150 trades affords more grounds for putting the system into service than a system estimated on only 15 trades.


Mathematical Expectation and Dispersion as Risk Estimate.


The two most important characteristics of a distribution are mathematical expectation (average) and dispersion. The standard normal distribution has a mathematical expectation equal to zero. At that, the distribution center is located at zero, as well. Flatness or steepness of normal distribution is characterized by the measure of spread of a random value within the mathematical expectation area. It is dispersion that shows us how values are spread about the random value's mathematical expectation.


Mathematical expectation can be found in a very simple way: For countable sets, all distribution values are summed up, the obtained sum being divided by the amount of values. For example, a set of natural numbers is infinite, but countable, since each value can be collated with its index (order number). For uncountable sets, integration will be applied. To estimate mathematical expectation of a series of trades, we will sum up all trade results and divide the obtained amount by the amount of trades. The obtained value will show the expected average result of each trade. If mathematical expectation is positive, we profit in average. If it is negative, we lose in average.


Figura 2. Chart of probability density of normal distribution.


The measure of spread of the distribution is the sum of squared deviations of the random value from its mathematical expectation. This characteristic of the distribution is called dispersion. Normally, mathematical expectation for a randomly distributed value is named M(X). Then dispersion may be described as D(X) = M((X-M(X))^2 ). The square root of dispersion is named standard deviation. It is also defined as sigma (σ). It is a normal distribution having mathematical expectation equal to zero and standard deviation equal to 1 that is named normal, or Gaussian, distribution.


The higher the value of standard deviation is, the more changeable the trading capital is, the higher its risk is. If the mathematical expectation is positive (a profitable strategy) and equal to $100 and if the standard deviation is equal to $500, we risk a sum, which is several times larger, to earn each dollar. For example, we have the results of 30 trades:


To find the mathematical expectation for this sequence of trades, let us sum up all the results and divide this by 30. We will obtain mean value M(X) equal to $4.26. To find the standard deviation, let us subtract the average from each trade's result, square it, and find the sum of squares. The obtained value will be divided by 29 (the amount of trades minus one). So we will obtain dispersion D equal to 9 353.623. Having generated square root of the dispersion, we obtain standard deviation, sigma, equal to $96.71.


The check data are given in the table below:


(Square of Difference)


What we have obtained is the mathematical expectation equal to $4.26 and standard deviation of $96.71. It is not the best ratio between the risk and the average trade. Profit chart below confirms this:


Fig.3. Balance graph for trades made.


Do I Trade Randomly? Z-Score.


The assumption itself that profit gained as a result of a series of trades is random sounds sardonically for the most of traders. Having spent a lot of time searching for a successful trading system and observed that the system found has already resulted in some real profits on a rather limited period of time, the trader supposes to have found a proper approach to the market. How can he or she assume that all this was just a randomness? That's a bit too thick, especially for newbies. Nevertheless, it is essential to estimate the results objectively. In this case, normal distribution, again, comes to the rescue.


We don't know what there will be each trade's result. We can only say that we either gain profit (+) or meet with losses (-). Profits and losses alternate in different ways for different trading systems. For example, if the expected profit is 5 times less than the expected loss at triggering of Stop Loss, it would be reasonable to presume that profitable trades (+ trades) will significantly prevail over the losing ones (- trades). Z - Score allows us to estimate how often profitable trades are alternated with losing ones.


Z for a trading system is calculated by the following formula:


N - total amount of trades in a series;


R - total amount of series of profitable and losing trades;


W - total amount of profitable trades in the series;


L - total amount of losing trades in the series.


A series is a sequence of pluses followed by each other (for example, +++) or minuses followed by each other (for example, --). R counts the amount of such series.


Fig.4. Comparison of two series of profits and losses.


In Fig. 4, a part of the sequence of profits and losses of the Expert Advisor that took the first place at the Automated Trading Championship 2006 is shown in blue. Z-score of its competition account has the value of -3.85, probability of 99.74% is given in brackets. This means that, with a probability of 99.74%, trades on this account had a positive dependence between them (Z-score is negative): a profit was followed by a profit, a loss was followed by a loss. Is this the case? Those who were watching the Championship would probably remember that Roman Rich placed his version of Expert Advisor MACD that had frequently opened three trades running in the same direction.


A typical sequence of positive and negative values of the random value in normal distribution is shown in red. We can see that these sequences differ. However, how can we measure this difference? Z-score answer this question: Does your sequence of profits and losses contain more or fewer strips (profitable or losing series) than you can expect for a really random sequence without any dependence between trades? If the Z-score is close to zero, we cannot say that trades distribution differs from normal distribution. Z-score of a trading sequence may inform us about possible dependence between consecutive trades.


At that, the values of Z are interpreted in the same way as the probability of deviation from zero of a random value distributed according to the standard normal distribution (average=0, sigma=1). If the probability of falling a normally distributed random value within the range of ±3σ is 99.74%, the falling of this value outside of this interval with the same probability of 99.74% informs us that this random value does not belong to this given normal distribution. This is why the "3-sigma rule'' is read as follows: a normal random value deviates from its average by no more than 3-sigma distance.


Sign of Z informs us about the type of dependence. Plus means that it is most probably that the profitable trade will be followed by a losing one. Minus says that the profit will be followed by a profit, a loss will be followed by a loss again. A small table below illustrates the type and the probability of dependence between trades as compared to normal distribution.


A positive dependence between trades means that a profit will cause a new profit, whereas a loss will cause a new loss. A negative dependence means that a profit will be followed by a loss, whereas the loss will be followed by a profit. The dependence found allows us to regulate sizes of positions to be opened (ideally) or even skip some of them and open them only virtually in order to watch trade sequences.


Holding Period Returns (HPR)


In his book, The Mathematics of Money Management, Ralph Vince uses the notion of HPR (holding period returns). A trade resulted in profit of 10% has the HPR=1+0.10=1.10. A trade resulted in a loss of 10% has the HPR=1-0. 10=0.90. You can also obtain the value of HPR for a trade by dividing the balance value after the trade has been closed (BalanceClose) by the balance value at opening of the trade (BalanceOpen). HPR=BalanceClose/BalanceOpen. Thus, every trade has both a result in money terms and a result expressed as HPR. This will allow us to compare systems independently on the size of traded contracts. One of indexes used in such comparison is the arithmetic average, AHPR (average holding period returns).


To find the AHPR, we should sum up all the HPRs and divide the result by the amount of trades. Let's consider these calculations using the above example of 30 trades. Suppose we started trading with $500 on the account. Let's make a new table:


AHPR will be found as the arithmetic average. It is equal to 1.0217. In other words, we averagely earn (1.0217-1)*100%=2.17% on each trade. Is this the case? If we multiply 2.17 by 30, we will see that the income should make 65.1%. Let's multiply the initial amount of $500 by 65.1% and obtain $325.50. At the same time, the real profit makes (627.71-500)/500*100%=25.54%. Thus, the arithmetic average of HPR does not always allow us to estimate a system properly.


Along with arithmetic average, Ralph Vince introduces the notion of geometric average that we shall call GHPR (geometric holding period returns), which is practically always less than the AHPR. The geometric average is the growth factor per game and is found by the following formula:


N - amount of trades;


BalanceOpen - initial state of the account;


BalanceClose - final state of the account.


The system having the largest GHPR will make the highest profits if we trade on the basis of reinvestment. The GHPR below one means that the system will lose money if we trade on the basis of reinvestment. A good illustration of the difference between AHPR and GHPR can be sashken's account history. He was the Championship's leader for a long time. AHPR = 9.98% impresses, but the final GHPR=-27.68% puts everything into perspective.


Sharpe Ratio.


Efficiency of investments is often estimated in terms of profits dispersion. One of such indexes is Sharpe Ratio. This index shows how AHPR decreased by the risk-free rate (RFR) relates to standard deviation (SD) of the HPR sequence. The value of RFR is usually taken as equal to interest rate on deposit in the bank or interest rate on treasury obligations. In our example, AHPR=1.0217, SD(HPR)=0.17607, RFR=0.


AHPR - average holding period returns;


RFR - risk-free rate;


SD - standard deviation.


Sharpe Ratio=(1.0217-(1+0))/0.17607=0.0217/0.17607=0.1232. For normal distribution, over 99% of random values are within the range of ±3σ (sigma=SD) about the mean value M(X). It follows that the value of Sharpe Ratio exceeding 3 is very good. In Fig. 5 below, we can see that, if the trade results are distributed normally and Sharpe Ratio=3, the probability of losing is below 1% per trade according to 3-sigma rule.


Fig.5. Normal distribution of trade results with the losing probability of less than 1%.


The account of Participant named RobinHood confirms this: his EA made 26 trades at the Automated Trading Championship 2006 without any losing one among them. Sharpe Ratio=3.07!


Linear Regression (LR) and Coefficient of Linear Correlation (CLC)


There is also another way to estimate trade results stability. Sharpe Ratio allows us to estimate the risk the capital is running, but we can also try to estimate the balance curve smooth degree. If we impose the values of balance at closing of each trade, we will be able to draw a broken line. These points can be fitted with a certain straight line that will show us the mean direction of capital changes. Let us consider an example of this opportunity using the balance graph of Expert Advisor Phoenix_4 developed by Hendrick.


Fig. 6. Balance graph of Hendrick, the Participant of the Automated Trading Championship 2006.


We have to find such coefficients a and b that this line goes as close as possible to the points being fitted. In our case, x is the trade number, y is the balance value at closing the trade.


Coefficients of an approximating straight are usually found by least squares method (LS method). Suppose we have this straight with known coefficients а and b. For every x, we have two values: y(x)=a*x+b and balance(x). Deviation of balance(x) from y(x) will be denoted as d(x)=y(x)-balance(x). SSD (sum of squared deviations) can be calculated as SD=Summ . Finding the straight by LS method means searching for such a and b that SD is minimal. This straight is also named linear regression (LR) for the given sequence.


Fig. 7. Balance value deviation from the straight of y=ax+b.


Having obtained coefficients of the straight of y=a*x+b using the LS method, we can estimate the balance value deviation from the found straight in money terms. If we calculate the arithmetic average for sequence d(x), we will be certain that М(d(x)) is close to zero (to be more exact, it is equal to zero to some calculation accuracy degree). At the same time, the SSD of SD is not equal to zero and has a certain limited value. The square root of SD/(N-2) shows the spread of values in the Balance graph about the straight line and allows to estimate trading systems at identical values of the initial state of the account. We will call this parameter LR Standard Error .


Below are values of this parameter for the first 15 accounts in the Automated Trading Championship 2006:


However, the degree of approximation of the balance graph to a straight can be measured in both money terms and absolute terms. For this, we can use correlation rate. Correlation rate, r, measures the degree of correlation between two sequences of numbers. Its value may lie within the range of -1 to +1. If r=+1, it means that two sequences have identical behavior and the correlation is positive.


Fig. 8. Positive correlation example.


If r=-1, the two sequences change in opposition, the correlation is negative.


Fig. 9. Negative correlation example.


If r=0, it means that there is no dependence found between the sequences. It should be emphasized that r=0 does not mean that there is no correlation between the sequences, it just says that such a correlation has not been found. This must be remembered. In our case, we have to compare two sequences of numbers: одна последовательность из графика баланса, а вторая - соответствующие точки на прямой линейной регрессии.


Fig. 10. Values of balance and points on linear regression.


Below is the table representation of the same data:


Let's denote balance values as X and the sequence of points on the straight regression line as Y. To calculate the coefficient of linear correlation between sequences X and Y, it is necessary to find mean values M(X) and M(Y) first. Then we will create a new sequence T=(X-M(X))*(Y-M(Y)) and calculate its mean value as M(T)=cov(X, Y)=M((X-M(X))*(Y-M(Y))). The found value of cov(X, Y) is named covariance of X and Y and means mathematical expectation of product (X-M(X))*(Y-M(Y)). For our example, covariance value is 21 253 775.08. Please note that M(X) and M(Y) are equal and have the value of 21 382.26 each. It means that the Balance mean value and the average of the fitting straight are equal.


Y - linear regression;


M(X) - Balance mean value;


M(Y) - LR mean value.


The only thing that remains to be done is calculation of Sx and Sy. To calculate Sx, we will find the sum of values of (X-M(X))^2, i. e., find the SSD of X from its mean value. Remember how we calculated dispersion and the algorithm of LS method. As you can see they are all related. The found SSD will be divided by the amount of numbers in the sequence - in our case, 36 (from zero to 35) - and extract the square root of the resulting value. So we have obtained the value of Sx. The value of Sy will be calculated in the same way. In our example, Sx=5839. 098245 and Sy=4610. 181675.


N - amount of trades;


Y - linear regression;


M(X) - Balance mean value;


M(Y) - LR mean value.


Now we can find the value of correlation coefficient as r=21 253 775.08/(5839. 098245*4610. 181675)=0.789536583. This is below one, but far from zero. Thus, we can say that the balance graph correlates with the trend line valued as 0.79. By comparison to other systems, we will gradually learn how to interpret the values of correlation coefficient. At page "Reports" of the Championship, this parameter is named LR correlation. The only difference made to calculate this parameter within the framework of the Championship is that the sign of LR correlation indicates the trade profitability.


The matter is that we could calculate the coefficient of correlation between the balance graph and any straight. For purposes of the Championship, it was calculated for ascending trend line, hence, if LR correlation is above zero, the trading is profitable. If it is below zero, it is losing. Sometimes an interesting effect occurs where the account shoes profit, but LR correlation is negative. This can mean that trading is losing, anyway. An example of such situation can be seen at Aver's. The Total Net Profit makes $2 642, whereas LR сorrelation is -0.11. There is likely no correlation, in this case. It means we just could not judge about the future of the account.


MAE and MFE Will Tell Us Much.


We are often warned: "Cut the losses and let profit grow". Looking at final trade results, we cannot draw any conclusions about whether protective stops (Stop Loss) are available or whether the profit fixation is effective. We only see the position opening date, the closing date and the final result - a profit or a loss. This is like judging about a person by his or her birth and death dates. Without knowing about floating profits during every trade's life and about all positions as a total, we cannot judge about the nature of the trading system. Quão arriscada é isso? How was the profit reached? Was the paper profit lost? Answers to these questions can be rather well provided by parameters MAE (Maximum Adverse Excursion) and MFE (Maximum Favorable Excursion).


Every open position (until it is closed) continuously experiences profit fluctuations. Every trade reached its maximal profit and its maximal loss during the period between its opening and closing. MFE shows the maximal price movement in a favorable direction. Respectively, MAE shows the maximal price movement in an adverse direction. It would be logical to measure both indexes in points. However, if different currency pairs were traded, we will have to express it in money terms.


Every closed trade corresponds to its result (return) and two indexes - MFE and MAE. If the trade resulted in profit of $100, MAE reaching -$1000, this does not speak for this trade's best. Availability of many trades resulted in profits, but having large negative values of MAE per trade, informs us that the system just "sits out" losing positions. Such trading is fated to failure sooner or later.


Similarly, values of MFE can provide some useful information. If a position was opened in a right direction, MFE per trade reached $3000, but the trade was then closed resulting in the profit of $500, we can say that it would be good to elaborate the system of unfixed profit protection. This may be Trailing Stop that we can move after the price if the latter one moves in a favorable direction. If short profits are systematic, the system can be significantly improved. MFE will tell us about this.


For visual analysis to be more convenient, it would be better to use graphical representation of distribution of values of MAE and MFE. If we impose each trade into a chart, we will see how the result has been obtained. For example, if we have another look into "Reports" of RobinHood who didn't have any losing trades at all, we will see that each trade had a drawdown (MAE) from -$120 to -$2500.


Fig. 11. Trades distribution on the plane of MAExReturns.


Besides, we can draw a straight line to fit the Returns x MAE distribution using the LS method. In Fig. 11, it is shown in red and has a negative slope (the straight values decrease when moving from left to right). Parameter Correlation(Profits, MAE)=-0.59 allows us to estimate how close to the straight the points are distributed in the chart. Negative value shows negative slope of the fitting line.


If you look through other Participants' accounts, you will see that correlation coefficient is usually positive. In the above example, the descending slope of the line says us that it tends to get more and more drawdowns in order not to allow losing trades. Now we can understand what price has been paid for the ideal value of parameter LR Correlation=1!


Similarly, we can build a graph of distribution of Returns and MFE, as well as find the values of Correlation(Profits, MFE) = 0.77 and Correlation(MFE, MAE) = -0.59. Correlation(Profits, MFE) is positive and tends to one (0.77). This informs us that the strategy tries not to allow long "sittings out" floating profits. It is more likely that the profit is not allowed to grow enough and trades are closed by Take Profit. As you can see, distributions of MAE and MFE дgive us a visual estimate and values of Correlation(Profits, MFE) and Correlation(Profits, MAE) can inform us about the nature of trading, even without charts.


Values of Correlation(MFE, MAE), Correlation(NormalizedProfits, MAE) and Correlation(NormalizedProfits, MFE) in the Championship Participants' "Reports" are given as additional information.


Trade Result Normalization.


In development of trading systems, they usually use fixed sizes for positions. This allows easier optimization of system parameters in order to find those more optimal on certain criteria. However, after the inputs have been found, the logical question occurs: What sizing management system (Money Management, MM) should be applied. The size of positions opened relates directly to the amount of money on the account, so it would not be reasonable to trade on the account with $5 000 in the same way as on that with $50 000. Besides, an ММ system can open positions, which are not directly proportional. I mean a position opened on the account with $50 000 should not necessarily be 10 times more than that opened on a $5 000 deposit.


Position sizes may also vary according to the current market phase, to the results of the latest several trades analysis, and so on. So the money-management system applied can essentially change the initial appearance of a trading system. How can we then estimate the impact of the applied money-management system? Was it useful or did it just worsen the negative sides of our trading approach? How can we compare the trade results on several accounts having the same deposit size at the beginning? A possible solution would be normalization of trade results.


TradeProfit - profit per trade in money terms;


TradeLots - position size (lots);


MinimumLots - minimum allowable position size.


Normalization will be realized as follows: We will divide each trade's result (profit or loss) by the position volume and then multiply by the minimum allowable position size. For example, order #4399142 BUY 2.3 lots USDJPY was closed with the profit of $4 056. 20 + $118.51 (swaps) = $4 174.71. This example was taken from the account of GODZILLA (Nikolay Kositsin). Let's divide the result by 2.3 and multiply by 0.1 (the minimum allowable position size), and obtain a profit of $4 056.20/2.3 * 0.1 = $176.36 and swaps = $5.15. these would be results for the order of 0.1-lot size. Let us do the same with results of all trades and we will then obtain Normalized Profits (NP).


the first thing we think about is finding values of Correlation(NormalizedProfits, MAE) and Correlation(NormalizedProfits, MFE) and comparing them to the initial Correlation(Profits, MAE) and Correlation(Profits, MFE). If the difference between parameters is significant, the applied method has likely changed the initial system essentially. They say that applying of ММ can "kill" a profitable system, but it cannot turn a losing system into a profitable one. in the Championship, the account of TMR is a rare exception where changing Correlation(NormalizedProfits, MFE) value from 0.23 to 0.63 allowed the trader to "close in black".


How Can We Estimate the Strategy's Aggression?


We can benefit even more from normalized trades in measuring of how the MM method applied influences the strategy. It is obvious that increasing sizes of positions 10 times will cause that the final result will differ from the initial one 10 times. And what if we change the trade sizes not by a given number of times, but depending on the current developments? Results obtained by trust-managing companies are usually compared to a certain model, usually - to a stock index. Beta Coefficient shows by how many times the account deposit changes as compared to the index. If we take normalized trades as an index, we will be able to know how much more volatile the results became as compared to the initial system (0.1-lot trades).


Thus, first of all, we calculate covariance - cov(Profits, NormalizedProfits). then we calculate the dispersion of normalized trades naming the sequence of normalized trades as NP. For this, we will calculate the mathematical expectation of normalized trades named M(NP). M(NP) shows the average trade result for normalized trades. Then we will find the SSD of normalized trades from M(NP), i. e., we will sum up (NP-M(NP))^2. The obtained result will be then divided by the amount of trades and name D(NP). This is the dispersion of normalized trades. Let's divide covariance between the system under measuring, Profits, and the ideal index, NormalizedProfits cov(Profits, NormalizedProfits), by the index dispersion D(NP). The result will be the parameter value that will allow us to estimate by how many times more volatile the capital is than the results of original trades (trades in the Championship) as compared to normalized trades. This parameter is named Money Compounding in the "Reports". It shows the trading aggression level to some extent.


Profits - trade results;


NP - normalized trade results;


M(NP) - mean value of normalized trades.


Now we can revise the way we read the table of Participants of the Automated Trading Championship 2006:


The LR Standard error in Winners' accounts was not the smallest. At the same time, the balance graphs of the most profitable Expert Advisors were rather smooth since the LR Correlation values are not far from 1.0. The Sharpe Ratio lied basically within the range of 0.20 to 0.40. The only EA with extremal Sharpe Ratio=3.07 turned not to have very good values of MAE and MFE.


The GHPR per trade is basically located within the range from 1.5 to 3%. At that, the Winners did not have the largest values of GHPR, though not the smallest ones. Extreme value GHPR=12.77% says us again that there was an abnormality in trading, and we can see that this account experienced the largest fluctuations with LR Standard error=$9 208.08.


Z-score does not give us any generalizations about the first 15 Championship Participants, but values of |Z|>2.0 may draw our attention to the trading history in order to understand the nature of dependence between trades on the account. Thus, we know that Z=-3.85 for Rich's account was practically reached due to simultaneous opening of three positions. And how are things with ldamiani's account?


Finally, the last column in the above table, Money Compounding, also has a large range of values from 8 to 50, 50 being the maximal value for this Championship since the maximal allowable trade size made 5.0 lots, which is 50 times more than the minimal size of 0.1 lot. However, curiously enough, this parameter is not the largest at Winners. The Top Three's values are 17.27, 28.79 and 16.54. Did not the Winners fully used the maximal allowable position size? Yes, they did. the matter is, perhaps, that the MM methods did not considerably influence trading risks at general increasing of contract sizes. This is a visible evidence of that money management is very important for a trading system.


The 15th place was taken by payday. The EA of this Participant could not open trades with the size of more than 1. 0 lot due to a small error in the code. What if this error did not occur and position sizes were in creased 5 times, up to 5.0 lots? Would then the profit increase proportionally, from $4 588.90 to $22 944.50? Would the Participant then take the second place or would he experience an irrecoverable DrawDown due to increased risks? Would alexgomel be on the first place? His EA traded with only 1.0-лот trades, too. Or could vgc win, whose Expert Advisor most frequently opened trades of the size of less than 1.0 lot. All three have a good smooth balance graph. As you can see, the Championship's plot continues whereas it was over!


Conclusion: Don't Throw the Baby Out with the Bathwater.


Opinions differ. This article gives some very general approaches to estimation of trading strategies. One can create many more criteria to estimate trade results. Each characteristic taken separately will not provide a full and objective estimate, but taken together they may help us to avoid lopsided approach in this matter.


We can say that we can subject to a "cross-examination" any positive result (a profit gained on a sufficient sequence of trades) in order to detect negative points in trading. This means that all these characteristics do not so much characterize the efficiency of the given trading strategy as inform us about weak points in trading we should pay attention at, without being satisfied with just a positive final result - the net profit gained on the account.


Well, we cannot create an ideal trading system, every system has its benefits and implications. Estimation test is used in order not to reject a trading approach dogmatically, but to know how to perform further development of trading systems and Expert Advisors. In this regard, statistical data accumulated during the Automated Trading Championship 2006 would be a great support for every trader.


Traduzido do russo pela MetaQuotes Software Corp.


Subscribe to the FT to read: Financial Times Binary trading: System of risk and reward offers a simple alternative.


Torne-se um assinante do FT.


Mantenha-se a par dos importantes desenvolvimentos corporativos, financeiros e políticos em todo o mundo. Mantenha-se informado e encontre riscos e oportunidades emergentes com relatórios globais independentes, comentários de especialistas e análises em que você possa confiar.


Escolha a assinatura que é adequada para você.


Compre uma assinatura de teste digital para.


Não tem certeza de qual pacote escolher? Experimente o acesso total por 4 semanas.


$ 1.00 por 4 semanas *


Por 4 semanas, receba acesso digital Premium ilimitado às notícias comerciais confiáveis ​​e confiáveis ​​da FT.


Compre uma assinatura Digital padrão para.


Seja informado com as notícias e opiniões essenciais.


MyFT - rastreie os tópicos mais importantes para você FT Weekend - acesso completo ao conteúdo do fim de semana Mobile & Table Apps - faça o download para ler em frente Artigo de presente - compartilhe até 10 artigos por mês com familiares, amigos e colegas.


Compre uma assinatura Premium Digital para.


Todos os itens essenciais, além de insights e análises mais profundas.


Todos os benefícios do Standard plus:


Lex - a nossa agenda que define a coluna diária Análise aprofundada - sobre comércio, mercados emergentes, M & A, investimento e mais ePaper - uma réplica digital do jornal Artigo de presente - compartilhe até 20 artigos por mês com familiares, amigos e colegas.


Compre uma assinatura Premium Digital + Newspaper para.


FT Newspaper entregue diariamente mais acesso digital ilimitado.


Todos os benefícios do Premium plus:


O FT entregue à sua casa ou escritório de segunda a sábado, incluindo o documento FT Weekend e suplementos.


Acesso total ao FT para sua equipe ou empresa.


Acesse sua equipe.


Descontos por volume Acesso em mais de 60 plataformas de terceiros Pague com base no uso.


Outras opções.


O Financial Times e o seu jornalismo estão sujeitos a um regime de auto-regulação ao abrigo do Código de Prática Editorial da FT.

No comments:

Post a Comment