Comércio de opções bidirecionais


Negociação Direcional.


DEFINIÇÃO de 'Direcional Trading'


Negociação direcional refere-se a estratégias de negociação baseadas na avaliação do investidor do amplo mercado ou na direção de uma determinada segurança. Os investidores podem implementar uma estratégia de negociação direcional básica adotando uma posição comprada se o mercado ou o título estiver em alta, ou uma posição vendida se os preços estiverem em queda.


No Dinheiro.


Curta (ou posição curta)


Proteção Downside.


QUEBRANDO 'Negociação Direcional'


A negociação direcional é amplamente associada à negociação de opções, uma vez que várias estratégias podem ser usadas para capitalizar uma movimentação maior ou menor no mercado amplo ou em uma ação específica. Embora o comércio direcional exija que o trader tenha uma forte convicção sobre o mercado ou a direção de curto prazo da empresa, o negociador também precisa ter uma estratégia de mitigação de risco para proteger o capital de investimento se os preços se moverem na direção oposta.


A negociação direcional em ações precisa de um movimento relativamente grande para permitir que o trader cubra as comissões e os custos de negociação, e ainda tenha lucro. Mas com opções, por causa de sua alavancagem, a negociação direcional pode ser tentada mesmo se o movimento antecipado no estoque subjacente não for esperado ser grande.


Exemplo de negociação direcional.


Suponha que um investidor esteja otimista sobre a ação XYZ, que está sendo negociada a US $ 50 e espera que ela suba para US $ 55 nos próximos três meses. O investidor, portanto, compra 200 ações a US $ 50, com um stop-loss de US $ 48, caso a ação inverta a direção. Se a ação atingir a meta de US $ 55, ela poderá ser vendida a esse preço por um lucro bruto, antes das comissões, de US $ 1.000. (ou seja, lucro de $ 5 x 200 partilhas).


Se o XYZ for negociado até US $ 52 nos próximos três meses, o avanço esperado de 4% poderá ser pequeno demais para justificar a compra imediata do estoque. As opções podem oferecer ao investidor uma alternativa melhor para lucrar com o movimento modesto do XYZ.


O investidor espera que a XYZ (que está sendo negociada a US $ 50) se mova lateralmente nos próximos três meses, com uma meta de US $ 52 e uma meta de baixa de US $ 49. Eles poderiam vender opções de venda no dinheiro (ATM) com um preço de exercício de US $ 50 com vencimento em três meses e receber um prêmio de US $ 1,50. O investidor, portanto, escreve dois contratos de opção de venda (de 100 ações cada) e recebe um prêmio bruto de US $ 300 (ou seja, US $ 1,50 x 200). Se a XYZ aumentar para US $ 52 quando as opções expirarem em três meses, elas expirarão, e o investidor reterá o prêmio de US $ 300, menos as comissões. No entanto, se a XYZ negociar abaixo de US $ 50 no momento em que as opções expirarem, o investidor seria obrigado a comprar as ações a US $ 50.


Se o investidor estivesse extremamente otimista sobre o preço das ações da XYZ e quisesse alavancar seu capital comercial, eles também poderiam comprar opções de compra como alternativa à compra imediata do estoque. No geral, as opções oferecem uma flexibilidade muito maior para estruturar as negociações direcionais, em oposição às negociações longas e curtas em uma ação ou índice. (Para saber mais, consulte: Um Guia de Estratégias de Negociação de Opções para Iniciantes.)


Negociação Bidirecional e Hedge de Posições no MetaTrader 5 Usando a API do HedgeTerminal, Parte 2.


Índice.


Introdução.


Este artigo é uma continuação da primeira parte "Negociação Bidirecional e Hedging de Posições no MetaTrader 5 Usando o Painel do HedgeTerminal, Parte 1". Na segunda parte, discutiremos a integração de Expert Advisors e outros programas MQL5 com a biblioteca HedgeTerminalAPI. Leia este artigo para aprender a trabalhar com a biblioteca. Ele ajudará você a criar Expert Advisors de negociação bidirecional enquanto ainda trabalha em um ambiente comercial confortável e simples.


Além da descrição da biblioteca, o artigo aborda os fundamentos da negociação assíncrona e da programação multiencadeada. Essas descrições são dadas na terceira e quarta seções deste artigo. Portanto, este material será útil para os traders que não estão interessados ​​em negociações bidirecionais, mas que gostariam de descobrir algo novo sobre programação assíncrona e multi-thread.


O material apresentado abaixo é destinado a operadores algorítmicos experientes que conhecem a linguagem de programação MQL5. Se você não conhece o MQL5, leia a primeira parte do artigo, que contém diagramas e desenhos simples explicando o princípio geral da biblioteca e o painel do HedgeTerminal.


Capítulo 1. Interação de Expert Advisors com o HedgeTerminal e seu painel.


1.1. Instalação de HedgeTermianlAPI. O primeiro começo da biblioteca.


O processo de instalação do HedgeTerminalAPI difere da instalação do painel visual HT, já que a biblioteca não pode ser executada sozinha no MetaTrader 5. Em vez disso, você precisará desenvolver um Expert Advisor especial para chamar a função HedgeTerminalInstall () da biblioteca. Esta função irá definir um arquivo de cabeçalho especial Prototypes. mqh descrevendo as funções disponíveis no HedgeTerminalAPI.


Uma biblioteca é instalada em um computador em três etapas:


Etapa 1. Faça o download da biblioteca HedgeTerminalAPI no seu computador. Localização da biblioteca em relação ao seu terminal: \ MQL5 \ Experts \ Market \ HedgeTerminalApi. ex5.


Etapa 2. Crie um novo Expert Advisor no Assistente MQL5 usando um modelo padrão. O Assistente MQL5 gera o seguinte código-fonte:


Etapa 3. Você precisará de apenas uma função do Expert Advisor - OnInit () resultante e da diretiva de exportação que descreve a função especial do instalador HedgeTerminalInstall () exportada pela biblioteca HedgeTerminalApi. Execute esta função diretamente na função OnInit (). O código-fonte marcado em amarelo executa estas operações:


Etapa 4. Suas ações adicionais dependem de você ter comprado a biblioteca. Se você comprou, você pode executar o Expert Advisor em tempo real diretamente no gráfico. Isso iniciará o instalador padrão de toda a linha de produtos do HedgeTerminal. Você pode concluir esta etapa facilmente seguindo as instruções descritas nas seções 2.1 e 2.2 do artigo "Negociação bidirecional e cobertura de posições no MetaTrader 5 usando o painel do HedgeTerminal, parte 1". O assistente de instalação instala todos os arquivos necessários, incluindo o arquivo de cabeçalho e o Expert Advisor de teste em seu computador.


Se você não comprou a biblioteca e deseja apenas testá-la, a operação do EA em tempo real não estará disponível para você, mas você pode testar a API executando o EA no testador de estratégia. O instalador não será executado neste caso. No modo de teste, o HedgeTermianalAPI funciona em um modo de usuário único, portanto, não precisa dos arquivos instalados no modo normal. Isso significa que você não precisa configurar mais nada.


Assim que o teste do EA for concluído, a pasta \ HedgeTerminal será criada na pasta comum do terminal. O caminho normal para o diretório comum dos terminais do MetaTrader é c: \ Users \ & lt; Nome de usuário & gt; \ AppData \ Roaming \ MetaQuotes \ Terminal \ Common \ Files \ HedgeTerminal \, onde & lt; Nome de usuário & gt; é o nome da sua conta de computador atual. A pasta \ HedgeTerminal já contém os arquivos \ MQL5 \ Include \ Prototypes. mqh e \ MQL5 \ Experts \ Chaos2.mq5. Copie esses arquivos nos mesmos diretórios do seu terminal: arquivo Prototypes. mqh para \ MetaTrader5 \ MQL5 \ Include e arquivo Chaos2.mq5 para \ MetaTrader5 \ MQL5 \ Experts.


O arquivo Prototypes. mqh é um arquivo de cabeçalho contendo a descrição das funções exportadas da biblioteca HedgeTerminalAPI. Seu propósito e descrições estão contidos em comentários para eles.


O arquivo Chaos2.mq5 contém um exemplo de EA descrito na seção "A função SendTradeRequest e a estrutura HedgeTradeRequest através do exemplo do EA do Chaos II". Desta forma, você pode entender visualmente como funciona o HedgeTerminalAPI e como desenvolver um Expert Advisor utilizando a tecnologia de virtualização do HedgeTerminal.


Os arquivos copiados estão disponíveis para seus EAs. Portanto, você só precisa incluir o arquivo de cabeçalho no código-fonte do Expert Advisor para começar a usar a biblioteca. Aqui está um exemplo:


Por exemplo, o código acima obtém o número total de posições ativas e exibe o número na guia "Especialistas" do terminal MetaTrader 5.


É importante entender que o HedgeTerminal é inicializado na primeira chamada de uma de suas funções. Essa inicialização é chamada de lenta. Portanto, a primeira chamada de uma de suas funções pode levar muito tempo. Se você quiser uma resposta rápida durante a primeira execução, você deve inicializar HT antecipadamente, por exemplo, você pode chamar a função TransactionTotal () no bloco de OnInit ().


Com a inicialização lenta, você pode omitir a inicialização explícita do Expert Advisor. Isso simplifica muito o trabalho com o HedgeTerminal e torna desnecessário configurá-lo previamente.


1.2. Integração de Expert Advisors com o HedgeTerminal Panel.


Se você tiver o painel visual HedgeTerminal e a versão completa da biblioteca, que pode ser executada em tempo real, você pode integrar seus Expert Advisors com o painel, de modo que todas as operações comerciais realizadas por eles também apareçam no painel. Em geral, a integração não é visível. Se você usar as funções HedgeTermianalAPI, as ações executadas pelos robôs serão exibidas automaticamente no painel. No entanto, você pode expandir a visualidade, indicando o nome EA em cada transação confirmada. Você pode fazê-lo removendo o comentário da linha abaixo no arquivo Settings. xml:


Esta tag está nas seções & lt; Active-Position & gt; e & lt; Posição do histórico & gt; .


Agora, os comentários são removidos e as tags são incluídas no processamento. Após o reinício do painel, a nova coluna "Magic" aparecerá nas tabelas das posições ativa e histórica. A coluna contém o número mágico do Expert Advisor, ao qual a posição pertence.


Se você quiser mostrar o nome do EA em vez de seu número mágico, inclua o nome no arquivo de alias ExpertAliases. xml. Por exemplo, o número mágico de um EA é 123847 e você deseja exibir seu nome, como "ExPro 1.1", adicione a seguinte tag ao arquivo:


Se for feito corretamente, o nome do EA será exibido em vez de sua mágica na coluna apropriada:


Fig. 1. Exibindo o nome EA em vez de Magic.


Observe que o painel e os Expert Advisors se comunicam em tempo real. Isso significa que se você fechar a posição de um EA diretamente no painel, o EA saberá sobre isso com a próxima chamada da função TransactionsTotal (). E vice-versa: depois que o Expert Advisor fecha sua posição, ele desaparece imediatamente da guia de posições ativas.


1.3. Princípios Gerais da Operação HedgeTerminalAPI.


Além das posições bidirecionais, o HedgeTerminal também trabalha com outros tipos de negociação, como ordens pendentes, transações e operações de corretagem. O HedgeTerminal trata todos esses tipos como um único grupo de transações. Uma transação, uma ordem pendente, uma posição direcional - todas elas são transações. No entanto, uma transação não pode existir sozinha. Em termos de programação orientada a objetos, uma transação pode ser introduzida como uma classe base abstrata, a partir da qual todas as entidades comerciais possíveis, como transações e posições bidirecionais, são herdadas. A este respeito, todas as funções do HedgeTerminalAPI podem ser divididas em vários grupos:


Pesquisa de transação e funções de seleção. A assinatura comum das funções e a maneira como elas funcionam quase que completamente coincidem com as funções OrderSend () e OrderSelect () no MetaTrader 4; Funções para obter propriedades de uma transação selecionada. Toda transação possui um conjunto específico de propriedades e funções específicas para seleção de propriedades. A assinatura comum das funções e a maneira como elas funcionam se assemelham às funções do sistema MetaTrader 5 em como elas acessam posições, ofertas e pedidos (como OrderGetDouble () ou HistoryDealGetInteger ()); HedgeTerminalAPI usa apenas uma função de negociação: SendTradeRequest (). Esta função permite fechar uma posição bidirecional ou parte dela. A mesma função é usada para modificar o stop loss, take profit ou o comentário de saída. Trabalhar com a função é semelhante ao OrderSend () no MetaTrader 5; A função para obter erros comuns GetHedgeError (), funciona para análise detalhada das ações de negociação do HedgeTerminal: TotalActionsTask () e GetActionResult (). Também usado para detecção de erros. Não há análogos no MetaTrader 4 ou MetaTrader 5.


Trabalhar com quase todas as funções é semelhante ao uso das funções do sistema MetaTrader 4 e MetaTrader 5. Como regra, a entrada de função é algum identificador (valor de enumeração) e a função retorna um valor que corresponde a ela.


Enumerações específicas estão disponíveis para cada função. A assinatura de chamada comum é a seguinte:


Vamos considerar um exemplo de como obter um identificador de posição exclusivo. É assim que fica a linha no MetaTrader 5:


No HedgeTerminal, receber um identificador exclusivo de uma posição bidirecional é o seguinte:


Os princípios gerais das funções são os mesmos. Apenas tipos de enumerações diferem.


1.4. Selecionando Transações.


A seleção de uma transação está passando pela lista de transações, que é semelhante à busca de pedidos no MetaTrader 4. No entanto, no MetaTrader 4 apenas os pedidos são procurados, enquanto no HedgeTerminal tudo pode ser encontrado como uma transação - como uma ordem pendente ou uma posição de cobertura. Portanto, cada transação deve primeiro ser selecionada usando a função TransactionSelect () e, em seguida, seu tipo deve ser identificado por meio de TransactionType ().


Duas listas de transações estão disponíveis até a data: transações ativas e históricas. A lista a ser aplicada é definida com base no modificador ENUM_MODE_TRADES. É semelhante ao modificador MODE_TRADES no MetaTrader 4.


O algoritmo de busca e seleção de transações é o seguinte:


O código percorre a lista de transações ativas no ciclo para (linha 1). Antes de prosseguir com a transação, selecione-a usando TransactionSelect () (linha 3). Apenas posições bidirecionais são selecionadas dessas transações (linha 4). Se o número mágico da posição e seu símbolo não corresponderem ao número mágico do EA atual e ao símbolo em que está sendo executado, o HT passa para a próxima posição (linhas 5 e 6). Em seguida, define o identificador de posição exclusivo (linha 8).


Atenção especial deve ser dada à linha 7. As posições selecionadas devem ser verificadas em termos de possibilidade de modificação. Se a posição já estiver no processo de modificação, ela não poderá ser alterada no encadeamento atual, embora você possa obter uma de suas propriedades. Se a posição estiver bloqueada, aguarde até que seja liberada para acessar suas propriedades ou tente modificá-la novamente. A propriedade HEDGE_POSITION_STATE é usada para descobrir se a modificação de posição é possível.


O modificador POSITION_STATE_FROZEN indica que a posição está "congelada" e não pode ser alterada. O modificador POSITION_STATE_ACTIVE mostra que uma posição está ativa e pode ser alterada. Esses modificadores são listados na enumeração ENUM_HEDGE_POSITION_STATE, documentada na seção apropriada.


Se uma pesquisa através de transações históricas for necessária, o modificador MODE_TRADES nas funções TransactionTotal () e TransactionSelect () deve ser substituído por MODE_HISTORY.


Uma transação no HedgeTerminal pode ser aninhada em outra. Isso é muito diferente do conceito do MetaTrader 5, onde não há aninhamento. Por exemplo, a posição histórica bidirecional no HedgeTerminal consiste em duas ordens, cada uma das quais inclui um conjunto arbitrário de transações. O aninhamento pode ser representado da seguinte forma:


Fig. 2. Transações aninhadas.


O aninhamento de transações é claramente visto no painel visual do HedgeTerminal.


A imagem abaixo mostra os detalhes de uma posição do MagicEx 1.3:


Fig. 3. Transações aninhadas no painel HedgeTerminal.


Você pode acessar as propriedades de uma ordem específica ou uma transação na posição bidirecional.


Selecione uma transação histórica e certifique-se de que seja uma posição bidirecional; Selecione um dos pedidos desta posição usando HedgeOrderSelect (); Obtenha uma das propriedades da ordem selecionada: o número de transações que ela contém; Selecione uma das ofertas pertencentes à ordem pesquisando todas as transações. Obtenha a propriedade de transação desejada.


Observe que, após a transação ter sido selecionada, suas propriedades específicas ficam disponíveis para ela. Por exemplo, se a transação for um pedido, após a seleção por HedgeOrderSelect (), você poderá encontrar o número de transações para ele (HedgeOrderGetInter (HEDGE_ORDER_DEALS_TOTAL)) ou o preço médio ponderado de entrada (HedgeDealGetDouble (HEDGE_DEAL_PRICE_EXECUTED)).


Vamos descobrir o preço do acordo # 1197610, que está marcado em vermelho na captura de tela. Este acordo é parte da posição bidirecional do MagicEx 1.3 EA.


Através do código abaixo, o EA pode acessar sua posição e esta transação:


Após a execução do código, a seguinte entrada será criada na aba Experts do terminal MetaTrader 5:


O EA primeiro seleciona a posição # 5917888 e, em seguida, seleciona a ordem # 6389111 dentro da posição. Uma vez que o pedido é selecionado, o EA começa a procurar o número de transação 1197610. Quando a transação é encontrada, o EA obtém seu preço de execução e adiciona o preço no diário.


1.5. Como obter códigos de erro usando GetHedgeError ()


Erros e situações imprevistas podem ocorrer durante o trabalho com o ambiente HedgeTerminal. Erro ao obter e analisar funções são usadas nesses casos.


O caso mais simples quando você recebe um erro é quando se esquece de selecionar uma transação usando a função TransactionSelect (). A função TransactionType () retornará o modificador TRANS_NOT_DEFINED neste caso.


Para entender onde está o problema, precisamos obter o modificador do último erro. O modificador nos informará que agora a transação foi selecionada. O código a seguir faz isso:


Esta é a mensagem resultante:


O ID de erro sugere que nos esquecemos de selecionar uma transação antes de tentar obter seu tipo.


Todos os possíveis erros estão listados na estrutura ENUM_HEDGE_ERR.


1.6. Análise detalhada de negociação e identificação de erros usando TotalActionsTask () e GetActionResult ()


Além dos erros que ocorrem no processo de trabalho com o ambiente HedgeTerminal, erros de negociação podem ocorrer como resultado da chamada SendTradeRequest (). Esses tipos de erros são mais difíceis de lidar. Uma tarefa executada por SendTradeRequest () pode conter várias atividades de negociação (subtarefas). Por exemplo, para alterar o comentário de saída em uma posição ativa protegida por um nível de stop loss, você deve fazer duas ações de negociação:


Cancelar a ordem de parada pendente representando o nível de parada; Coloque uma nova ordem de parada pendente com um novo comentário no lugar do pedido anterior.


Se a nova ordem de parada for acionada, seu comentário será exibido como um comentário fechando a posição, o que é uma maneira correta.


No entanto, a tarefa pode ser executada em parte. Suponha que a ordem pendente seja cancelada com sucesso, mas a colocação de novo pedido falha por qualquer motivo. Nesse caso, a posição será deixada sem o nível de perda de parada. Para poder lidar com esse erro, o EA precisará chamar um log de tarefa especial e pesquisar nele para localizar a subtarefa que falhou.


Isso é feito usando duas funções: TotalActionsTask () retorna o número total de ações de negociação (subtarefas) dentro dessa tarefa; e GetActionResult () aceita o índice de subtarefas e retorna seu tipo e seu resultado de execução. Como todas as operações de negociação são realizadas usando ferramentas padrão do MetaTrader 5, o resultado de seu desempenho corresponde ao código de retorno do servidor de negociação.


Em geral, o algoritmo de busca pelo motivo da falha é o seguinte:


Obtendo o número total de subtarefas na tarefa usando TotalActionsTask (); Pesquisando por todas as subtarefas no loop for. Determinando o tipo de cada subtarefa e seu resultado.


Suponha que a ordem de parada com um novo comentário não pôde ser feita porque o preço de execução da ordem estava muito próximo do nível de preço atual.


O código de exemplo abaixo mostra como o EA pode encontrar o motivo dessa falha:


A seguinte mensagem aparecerá após a execução do código:


Comparando os números com os modificadores padrão dos códigos de retorno do servidor de negociação, descobrimos que o pedido pendente foi removido com sucesso, mas a colocação de um novo pedido falhou. O servidor de negociação retornou um erro 10015 (preço incorreto), o que pode significar que o preço atual está muito próximo do nível de parada.


Sabendo disso, o EA pode assumir o controle dos níveis de parada. Para fazer isso, o EA só terá que fechar essa posição usando a mesma função SendTradeRequest ().


1.7. Acompanhando o Status da Execução de Tarefas de Comércio.


Cada tarefa de negociação pode consistir em qualquer número de subtarefas que devem ser executadas sequencialmente.


No modo assíncrono, uma tarefa pode ser executada em várias etapas do código. Também pode haver casos em que a tarefa pode "congelar". Portanto, o controle da EA sobre a execução de tarefas é necessário. Ao chamar a função HedgePositionGetInteger () com o modificador HEDGE_POSITION_TASK_STATUS, ela retorna a enumeração do tipo ENUM_TASK_STATUS que contém o status da tarefa de posição atual.


Por exemplo, se algo der errado depois de enviar um pedido para fechar uma posição, devido a qual a posição não está fechada, você precisará obter o status da tarefa.


O exemplo a seguir mostra o código que um Expert Advisor assíncrono pode executar para analisar o status da tarefa para a posição:


Observe que a execução de algumas tarefas complexas requer várias iterações.


No modo assíncrono, eventos futuros que sinalizam mudanças no ambiente de negociação iniciam uma nova iteração. Assim, todas as iterações são executadas sem demora, uma após a outra, seguindo as respostas recebidas do servidor de negociação. A execução da tarefa é diferente no modo síncrono.


O método síncrono usa o emulador de operação síncrona, devido ao qual os usuários podem executar tarefas compostas em uma única passagem. O emulador usa atrasos de tempo. Por exemplo, após o início da execução de uma subtarefa, o emulador não retorna o encadeamento de execução para o EA. Em vez disso, aguarda algum tempo esperando que o ambiente de negociação mude. Depois disso, relê o ambiente de negociação novamente. Se entender que a subtarefa foi concluída com êxito, inicia as próximas subtarefas.


Esse processo reduz um pouco o desempenho geral, pois leva algum tempo para aguardar. Mas isso transforma a execução de tarefas complexas em uma operação seqüencial simples executada em uma única chamada de função. Portanto, você quase nunca precisa analisar o log de execução de tarefas no método síncrono.


1.8. Como modificar e fechar posições bidirecionais.


Posições bidirecionais são modificadas e fechadas usando a função SendTradeRequest (). Apenas três opções podem ser aplicadas a uma posição ativa:


Uma posição pode ser total ou parcialmente fechada; Posição stop loss e take profit podem ser modificados; O comentário de saída de uma posição pode ser alterado.


A posição histórica não pode ser alterada. Semelhante à função OrderSend () no MetaTrader 5, SendTradeRequest () usa uma consulta pré-compilada na forma de uma estrutura de negociação HedgeTraderRequest. Leia a documentação para obter mais detalhes sobre a função SendTradeRequest () e a estrutura HedgeTraderRequest. O exemplo que mostra a modificação e fechamento da posição está disponível na seção Chaos II EA.


1.9. Como definir as propriedades do HedgeTerminal de um Expert Advisor.


O HedgeTerminal possui um conjunto de propriedades, como frequência de atualização, o número de segundos para aguardar uma resposta do servidor e outros.


Todas essas propriedades são definidas em Settings. xml. Quando um EA é executado em tempo real, a biblioteca lê as propriedades do arquivo e define os parâmetros internos apropriados. Quando o EA é testado em um gráfico, o arquivo Settings. xml não é usado. No entanto, em algumas situações, você pode precisar modificar individualmente as propriedades do EA, independentemente de estar em execução em um gráfico ou no testador de estratégias.


Isso é feito através do conjunto especial de funções HedgePropertySet… A versão atual apresenta apenas um protótipo deste conjunto:


Por exemplo, para definir o tempo limite para a biblioteca aguardar uma resposta do servidor, escreva o seguinte:


Se a resposta do servidor não for recebida dentro de 30 segundos após o envio de uma solicitação assíncrona, a posição bloqueada será liberada.


1,10. Modos de funcionamento síncrono e assíncrono.


O HedgeTerminal e sua API executam atividades de negociação de forma totalmente assíncrona.


No entanto, este modo requer uma lógica mais complexa dos EAs. Para ocultar essa complexidade, o HedgeTerminalAPI inclui um emulador especial de operação síncrona, permitindo que os EAs desenvolvidos em um método síncrono convencional se comuniquem com algoritmos assíncronos do HedgeTerminalAPI. Essa interação é revelada no momento da modificação da posição bidirecional e do fechamento por SendTradeRequest (). Esta função permite executar uma tarefa de negociação no modo síncrono ou assíncrono. Por padrão, todas as ações de negociação são executadas de forma síncrona por meio do emulador de operação síncrona. No entanto, se uma solicitação de negociação (estrutura HedgeTradeRequest) contiver um sinalizador explicitamente especificado asynch_mode = true, a tarefa de negociação será executada em um modo assíncrono.


No modo assíncrono, as tarefas são executadas independentemente do thread principal. A implementação da interação entre um EA assíncrono e algoritmos assíncronos do HedgeTerminal ainda não está completa.


O emulador síncrono é muito simples. Ele inicia as subtarefas sequencialmente e aguarda por algum tempo até que o ambiente comercial no MetaTrader 5 seja alterado. O emulador analisa essas alterações e determina o status da tarefa atual. Se a execução da tarefa for bem sucedida, o emulador passa para o próximo.


O emulador síncrono causa pequenos atrasos na execução de ordens de negociação. Isto é devido ao fato de que o ambiente de negociação no MetaTrader 5 leva algum tempo para refletir as atividades de negociação executadas. A necessidade de acessar o ambiente é primariamente conectada ao fato de que o HedgeTermianlAPI não pode acessar eventos que chegam ao manipulador OnTradeTransaction () no modo de emulação de thread síncrono.


Os problemas de interação entre encadeamentos assíncronos, bem como entre encadeamentos assíncronos e síncronos por emulação, são muito complicados e não têm soluções óbvias.


1.11. Gerenciamento de propriedades de posição bidirecional através do exemplo de um script.


No script abaixo, a função TransactionSelect () pesquisa todas as transações disponíveis na lista de transações ativas.


Cada transação é selecionada na lista. Se a transação é uma posição, algumas de suas propriedades são acessadas e impressas. Além das propriedades das posições, as propriedades das ordens e ofertas dentro da posição também são impressas. Um pedido e uma transação são selecionados primeiro usando HedgeOrderSelect () e HedgeDealSelect () respectivamente.


Todas as propriedades da posição, suas ordens e transações são combinadas e impressas como uma única linha usando a função de sistema printf.


1.12. A função SendTradeRequest () e a estrutura HedgeTradeRequest através do exemplo do EA do Chaos II.


Como exemplo, vamos desenvolver um robô comercial baseado nas táticas de negociação propostas por Bill Williams em seu livro Trading Chaos. Segunda edição.


Não seguiremos todas as suas recomendações, mas simplificaremos o esquema omitindo o indicador Alligator e algumas outras condições. A escolha dessa estratégia decorre de várias considerações. A principal delas é que essa estratégia inclui táticas de manutenção de posição composta. Às vezes você precisa fechar uma parte de uma posição e mover o stop loss para breakeven.


Quando movido para ponto de equilíbrio, o nível de parada deve ser seguido pelo preço. A segunda consideração é que essa tática é bastante conhecida e os indicadores desenvolvidos para ela estão incluídos no pacote de entrega padrão do MetaTrader 5. Vamos modificar e simplificar um pouco as regras, para impedir que a lógica complexa do Expert Advisor atrapalhe seus objetivos principais: mostrar um exemplo de interação do EA com a biblioteca HedgeTerminalAPI. A lógica do EA usa a maioria das funções de negociação do HedgeTerminalAPI. Este é um bom teste para a biblioteca.


Vamos começar na barra de reversão. Uma barra de reversão de alta é uma barra com o preço de fechamento em seu terço superior, cujo Baixo é o menor para os últimos N barras. Uma barra de reversão de baixa é uma barra com o preço mais próximo em seu terço inferior, cuja Alta é a mais alta para os últimos N barras. N é um parâmetro escolhido aleatoriamente, pode ser definido durante o início do Expert Advisor. Isso difere da estratégia clássica "Caos 2".


Depois que a barra de reversão é definida, duas ordens pendentes são colocadas. Para uma barra de alta, as ordens são colocadas acima de sua alta, uma barra de baixa - logo abaixo de sua baixa. Se essas duas ordens não forem acionadas durante as barras OldPending, o sinal será considerado obsoleto e as ordens serão canceladas. Os valores de OldPending e N são definidos pelo usuário antes de iniciar o EA no gráfico.


As ordens disparam e se transformam em duas posições bidirecionais. O EA distingue entre eles por números nos comentários, "# 1" e "# 2", respectivamente. Esta não é uma solução muito elegante, mas é boa para fins de demonstração. Uma vez que as ordens são acionadas, uma perda de parada é colocada na alta (para uma barra de baixa) ou a baixa (se a barra de alta) da barra de reversão.


A primeira posição tem alvos apertados. Seu take profit é definido de modo que, no caso de acionamento, o lucro da posição seria igual à perda absoluta de uma perda de parada acionada. Por exemplo, se uma posição longa for aberta a um preço de 1.0000, e sua perda de parada estiver no nível de 0.9000, o nível de lucro obtido será 1.0000 + (1.0000 - 0.9000) = 1.1000. O EA sai da posição em stop loss ou take profit.


A segunda posição é de longo prazo. Seu stop loss é seguido pelo preço. A parada se move após o recém formado fractal de Bill Williams. Para uma posição longa, a parada é movida de acordo com os fractais inferiores e os fractais superiores são usados ​​para uma posição curta. O EA sai da posição apenas no stop loss.


O gráfico a seguir ilustra essa estratégia:


Fig. 4. A representação de posições bidirecionais do EA do Chaos 2 no gráfico de preços.


Barras de reversão são marcadas com uma moldura vermelha. O período N deste gráfico é igual a 2. O momento mais oportuno é escolhido para esta estratégia. As posições curtas são mostradas como uma linha pontilhada azul, as posições longas são representadas por verde. Como pode ser visto, posições longas e curtas podem existir simultaneamente, mesmo em uma estratégia relativamente simples. Preste atenção ao período de 5 a 8 de janeiro de 2014.


Este é um ponto de virada para a tendência de baixa do AUDCAD. 4 de janeiro um sinal foi recebido da barra de reversão de alta, e 5 de janeiro duas longas posições foram abertas. Ao mesmo tempo, havia ainda três posições curtas cujas paradas seguiam a tendência (linha vermelha tracejada). Então, em 7 de janeiro, pare de ser acionado para as posições curtas, então apenas posições longas foram deixadas no mercado.


Mudanças seriam difíceis de monitorar em uma posição líquida, uma vez que o volume líquido não levaria em conta o número de posições realmente mantidas pelo EA. O HedgeTerminal permite que os EAs monitorem suas posições individuais, independentemente da posição líquida atual, possibilitando obter esses gráficos e desenvolver estratégias semelhantes.


Abaixo está o código que implementa essa estratégia.


Eu intencionalmente não usei programação orientada a objetos, adaptando o código para iniciantes:


Abaixo está uma breve descrição de como esse código funciona. O EA é chamado em todos os carrapatos. Ele analisa a barra anterior usando a função BarIsExtremum (): se é baixa ou alta, coloca duas ordens pendentes (função SetNewPendingOrder ()). Uma vez ativadas, as ordens pendentes são convertidas em posições. O EA define stop loss e obtém lucro para as posições então.


Unfortunately, these levels cannot be placed together with pending orders, because there is no real position yet. The levels are set through the SupportPositions() function. To operate properly, we need to know the position for which take profit should be placed, and the position that should be trailed following fractals. This definition of positions is done by the IdentifySelectPosition() function. It analyzes the initiating position comment, and if it contains the string "#1", a tight target is set for it; if it contains "# 2", trailing stop is applied.


To modify an open bi-directional position, or to close it, a special trade request is created, which is then sent to the SendTradeRequest() function for execution:


Pay attention to error handling.


If sending fails and the function returns false , we need to get the last error code using the GetHedgeError() function. In some cases the execution of a trading order will not even start. If position has not been pre-selected, then the query is made incorrectly, and its execution is impossible.


If an order is not executed, it is pointless to analyze the log of its implementation, getting an error code is enough.


However, if the query is correct, but the order has not been executed for some reason, error HEDGE_ERR_TASK_FAILED will be returned. In this case, it is necessary to analyze the order execution log by searching through the log. This is done through the special function PrintTaskLog ():


These messages allow to identify the reason for the failure and fix it.


Let us now illustrate the display of the Chaos2 EA and its positions in HedgeTerminal in real time. The EA is running on the M1 chart:


Fig. 5. The representation of bi-directional positions of the Chaos 2 EA in the HedgeTerminal panel.


As can be seen, even bi-directional positions of one EA can perfectly coexist.


1.13. On "Duplicate Symbols" and Virtualization by Broker.


When MetaTrader 5 was released, some brokers started to provide the so-called duplicate symbols. Their quotes are equal to the original instruments, but they have a postfix as a rule, like "_m" or "_1" . They were introduced to allow traders to have bi-directional positions on virtually the same symbol.


However, such symbols are almost useless for algorithmic traders using robots. And here's why. Suppose we would need to write the "Chaos II" EA without the HedgeTerminalAPI library. Instead, we would have some duplicate symbols. How would we do that? Assume all sell operations were opened on a single instrument, such as EURUSD, and all buy operations on the other one, for example EURUSD_m1.


But what would happen if, at the moment of position opening one of the symbols were already traded by another robot or by the trader? Even if such symbols were always free, the problem would not be solved for this robot, which could simultaneously have multiple positions in the same direction.


The screenshot above shows three sell positions, and there can be even more of them. The positions have different protective stop levels, that is why they cannot be combined into a single net position. The solution is to open a new position for a new duplicate symbol. But there can be not enough such symbols, because one robot needs six duplicate instruments (three in each trade direction). If two robots run on different timeframes, 12 symbols are required.


None of the brokers provide so many duplicate symbols. But even if there were an unlimited amount of such symbols, and they were always free, a complex decomposition of the algorithm would be required. The robot would have to go through all the available symbols searching for duplicates and its own positions. This would create more problems than it could solve.


There are even more difficulties with the duplicate symbols. Here is a brief list of additional problems arising from their use:


You pay for each duplicate symbol in the form of negative swaps, because swaps for locking or partial locking are always negative, and this is the case when you keep two bi-directional positions on two different instruments. Not all brokers provide duplicate symbols. A strategy developed for a broker who provides duplicate symbols will not work with a broker providing only one instrument. The difference in the symbol names is another potential source of problems. Creating a duplicate symbol is not always possible. On transparent markets subject to strict regulations, any transaction is a financial document. The net position is the de facto standard in such markets and therefore creation of individual symbols is far from possible there. For example, no broker providing duplicate symbols can ever appear on Moscow Exchange MOEX. In less strict regulated markets brokers can create any symbols for their clients. Duplicate instruments are ineffective when trading using robots. The reasons for their ineffectiveness have been disclosed in the above example of the Chaos 2 EA.


A duplicate symbol is essentially a virtualization on the broker side. HedgeTerminal uses virtualization on the client side.


In both cases we use virtualization as such. It changes the actual representation of trader's obligations. With virtualization, one position can turn into two positions. There is no problem when it occurs on the client side, because clients can represent whatever they want. But if virtualization is done by the broker, regulatory and licensing organizations may have questions about how the information provided relates to the actual information. The second difficulty is that this requires having two APIs in one: a set of functions and modifiers for use in the net mode, and another one for the bi-directional mode.


Many algorithmic traders have found their own way to bind trades into a single position. Many of these methods work well, and there are articles describing these methods. However, virtualization of positions is a more complicated procedure than it might seem. In HedgeTerminal, the algorithms associated with virtualization of positions take about 20,000 lines of the source code. Moreover, HedgeTerminal implements only basic functions. Creating a similar amount of code in your EA only to accompany bi-directional positions would be too much resource consuming.


Chapter 2. HedgeTerminal API Manual.


2.1. Transaction Selection Functions.


The function returns the total number of transactions in the list of transactions. This is the basic function for searching though available transactions (see the example in section 1.4 and 1.11 of this article).


[in] pool=MODE_TRADES – Specifies the identifier of the data source for selection. It can be one of the values of the ENUM_MODE_TRADES enumeration.


The function returns the total number of transactions in the list of transactions.


The function returns the type of a selected transaction.


Return type. The value can be one of the ENUM_TRANS_TYPE values.


This function selects a transaction for further manipulations. The function selects a transaction by its index or unique identifier in the list of transactions.


[in] index – The index of the order in the list of orders or a unique identifier of the transaction depending on the 'select' parameter. [in] select=SELECT_BY_POS – Identifier of the 'index' type of the parameter. The value can be one of the ENUM_MODE_SELECT values. [in] pool=MODE_TRADES – Specifies the identifier of the data source for selection. It can be one of the values of the ENUM_MODE_TRADES enumeration.


Returns true if a transaction has been successfully selected or false otherwise. To get error details, call GetHedgeError().


If a transaction is selected based on its index, the complexity of the operation corresponds to O(1) . If a transaction is selected based on its unique identifier, the complexity of the operation asymptotically tends to O(log2(n)) .


The function selects one of the orders included in the bi-directional position. The bi-directional position, which includes the required order, must be pre-selected using TransactionSelect ().


[in] type – the identifier of the order to be selected. The value can be one of the ENUM_HEDGE_ORDER_SELECTED_TYPE enumeration values.


Returns true if an order has been successfully selected or false otherwise. To get error details, call GetHedgeError().


The function selects one of the deals that have executed the order. The order the part of which is the selected deal must be pre-selected using the HedgeOrderSelect() function.


[in] index – The index of the deal to be selected from the list of deals that executed the order. To find out the total number of deals inside one order, call the appropriate order property using the HedgeOrderGetInteger() function. For the parameter, use the ENUM_HEDGE_ORDER_PROP_INTEGER modifier equal to the HEDGE_ORDER_DEALS_TOTAL value.


Returns true if a deal has been successfully selected or false otherwise. To get error details, call GetHedgeError().


2.2. Functions for Getting Properties of a Selected Transaction.


The function returns the property of a selected bi-directional position. The property can be of type int , long , datetime or bool depending on the type of the requested property. The bi-directional position must be pre-selected using the TransactionSelect() function.


[in] property – Identifier of the property of the bi-directional position. The value can be one of the ENUM_HEDGE_DEAL_PROP_INTEGER enumeration values.


Valor do tipo ulong. For further use of the value, its type should be explicitly cast to the type of the requested property.


The function returns the property of a selected bi-directional position. The type of the return property is double . Property type is specified through the ENUM_HEDGE_POSITION_PROP_DOUBLE enumeration. The bi-directional position must be pre-selected using the TransactionSelect().


[in] property – Identifier of the property of the bi-directional position. The value can be one of the ENUM_HEDGE_DEAL_PROP_DOUBLE enumeration values.


The function returns the property of a selected bi-directional position. The property is of the string type. Property type is specified through the ENUM_HEDGE_POSITION_PROP_STRING enumeration. The bi-directional position must be pre-selected using the TransactionSelect().


[in] property – Identifier of the property of the bi-directional position. The value can be one of the ENUM_HEDGE_POSITION_PROP_STRING enumeration values.


A value of the string type.


The function returns the property of the selected order, which is part of the bi-directional position. The property can be of type int , long , datetime or bool . Property type is specified through the ENUM_HEDGE_ORDER_PROP_INTEGER enumeration. The order must be pre-selected using the HedgeOrderSelect() function.


[in] property – Identifier of the property of the order, which is part of the bi-directional position. The value can be one of the ENUM_HEDGE_ORDER_PROP_INTEGER enumeration values.


Valor do tipo ulong. For further use of the value, its type must be explicitly cast to the type of the requested property.


The function returns the property of the selected order, which is part of the bi-directional position. The requested property is of the double type. Property type is specified through the ENUM_HEDGE_ORDER_PROP_DOUBLE enumeration. The order must be pre-selected using the HedgeOrderSelect() function.


[in] property – Identifier of the property of the order, which is part of the bi-directional position. The value can be any of the ENUM_HEDGE_ORDER_PROP_DOUBLE enumeration values.


The function returns the property of the selected deal, which is part of the executed order. The property can be of type int , long , datetime or bool . Property type is specified through the ENUM_HEDGE_DEAL_PROP_INTEGER enumeration. The deal must be pre-selected using the HedgeDealSelect() function.


[in] property – Identifier of the property of the selected deal included in the executed order. The value can be one of the ENUM_HEDGE_DEAL_PROP_INTEGER enumeration values.


Valor do tipo ulong. For further use of the value, its type should be explicitly cast to the type of the requested property.


The function returns the property of the selected deal, which is part of the executed order. The property can be of type double . Property type is specified through the ENUM_HEDGE_DEAL_PROP_DOUBLE enumeration. The deal must be pre-selected using the HedgeDealSelect() function.


[in] property – Identifier of the property of the selected deal included in the executed order. The value can be one of the ENUM_HEDGE_DEAL_PROP_DOUBLE enumeration values.


2.3. Functions for Setting and Getting HedgeTerminal Properties from Expert Advisors.


The function sets one of the HedgeTerminal properties. The property can be of type int , long , datetime or bool . Property type is specified through the ENUM_HEDGE_PROP_INTEGER enumeration.


[in] property – Identifier of the property that should be set for HedgeTerminal. The value can be one of the ENUM_HEDGE_PROP_INTEGER enumeration values.


A value of type bool . If the property has been successfully set, the function returns true, otherwise it returns false.


In the example, the function is used to set the position locking time while sending an asynchronous request. If the server response is not received within 30 seconds after you send an asynchronous request, the blocked position will be unblocked.


The function gets one of the HedgeTerminal properties. The property can be of type int , long , datetime or bool . Property type is specified through the ENUM_HEDGE_PROP_INTEGER enumeration.


[in] property – Identifier of the property that should be received from HedgeTerminal. The value can be one of the ENUM_HEDGE_PROP_INTEGER enumeration values.


A value of type long .


The function receives the position blocking time while sending an asynchronous request and shows it in the terminal.


2.4. Functions for Getting and Handling Error Codes.


The function returns the identifier of the error, which was obtained from the last action. The error identifier corresponds to the ENUM_HEDGE_ERR enumeration.


Position ID. The value can be any of the ENUM_HEDGE_ERR enumeration type.


After the call, the GetHedgeError() function does not reset the error ID. To reset the error ID use the ResetHedgeError() function.


The function resets the identifier of the last received error. After its call, the ENUM_HEDGE_ERR identifier returned by GetHedgeError() will be equal to HEDGE_ERR_NOT_ERROR.


Once the position is selected using the HedgePositionSelect() function, it can be modified using the SendTradeRequest() function. For example, it can be closed, or its outgoing comment can be changed. This modification is performed by a special trading task . Each task can consist of several trading activities (subtasks). A task may fail. In this case you may need to analyze the result of all the subtasks included in the task to see what kind of the subtasks failed.


The TotalActionTask() function returns the number of subtasks contained in the last trading task being executed for the selected position. Knowing the total number of subtasks, you can search though all the subtasks by their index, and analyze their execution results using the GetActionResult() function and thereby find out the circumstances of the failure.


Retorna o número total de subtarefas dentro da tarefa.


The function takes the index of the subtask within the task (see TotalActionTask()). Returns the type of the subtask and its execution results through reference parameters. The type of the subtask is defined by the ENUM_TARGET_TYPE enumeration. The subtask execution result corresponds to the MetaTrader 5 trade server return codes.


[in] index – The index of the subtask in the list of subtasks. [out] target_type – Type of the subtask. The value can be one of the ENUM_TARGET_TYPE enumeration values. [out] retcode – Trade server return code received upon the subtask execution.


The function sends a request to change the selected bi-directional position in HedgeTerminalAPI. The function execution result is one of the three actions:


Closing a position or a part of its volume; Modification of stop loss and take profit levels; Modification of the outgoing comment.


The action type and its parameters are specified in the HedgeTradeRequest structure, which is passed by reference as a parameter. Before the function call, the bi-directional position must be pre-selected using the TransactionSelect() function.


[in] request – The structure of the request to modify the bi-directional position. Please see the structure description and the explanation of its fields in the description of the HedgeTradeRequest structure.


Returns true, if the request for position modification has been successfully executed. Returns false otherwise. In case of request execution failure, use functions TotalActionsTask() and GetActionResult() to find the failure and its reasons.


In the asynchronous mode of request sending, the return flag contains true if a task has been successfully placed and started. However, we must remember that even in the case of the successful start of a task, its execution cannot be guaranteed. Therefore this flag cannot be used to control task completion in the asynchronous mode. In the synchronous mode, a task is started and executed in a single thread, so in the synchronous mode, you can control the trade request execution result using this flag.


Trade Request Structure HedgeTradeRequest()


Bi-directional positions in HedgeTerminal are closed and modified through a call of the SendTradeRequest() function, in which the trade request is used as an argument. The request is represented by a special predefined structure HedgeTradeRequest, which contains all the fields necessary to close or modify the selected position:


Bi-Directional Trading and Hedging of Positions in MetaTrader 5 Using the HedgeTerminal Panel, Part 1.


Índice.


Introdução.


Within the last 18 months MetaQuotes have conducted extensive work on consolidating the MetaTrader 4 and MetaTrader 5 platforms into a unified trading ecosystem. Now both platforms share a common market of program solutions - Market, offering different products from external developers. The compilers for both platforms were united as well. As a result both platforms have a common compiler based on MQL5 and one programming language - MQL with a different function set depending on the platform in use. All publicly available source codes located in the Code Base were also revised and some of them were adjusted to be compatible with the new compiler.


This major unification of the platforms left aside the unification of their trading parts. The trading models of MetaTrader 4 and MetaTrader 5 are still fundamentally incompatible despite the fact that the major part of the trading environment is shared. MetaTrader 4 facilitates individual management of trading positions through the system of orders - special program entities making the bi-directional trading in this terminal simple and easy. MetaTrader 5 is intended for the exchange trade where the main representation of a trader's obligations is their aggregate net position. Orders in MetaTrader 5 are simply instructions to buy or sell a financial instrument.


The difference between the trading performance of these two platforms caused a lot of heated discussions and debates. However, discussions remained discussions. Unfortunately, since the release of MetaTrader 5, not a single working solution was published that could enable presenting a trader's obligations as bi-directed positions like in MetaTrader 4. Although numerous published articles suggest various solutions, they are not flexible enough to be conveniently used on a large scale. In addition, none of those decisions are suitable for the exchange trading, which involves a lot of nuances that have to be taken into consideration.


This article should settle the controversies between the fans of the fourth and the fifth versions of the MetaTrader platform. This is going to provide a universal solution in the form of thorough program specification and the exact program solution implemented by this specification. This article discusses a visual panel and the virtualization library HedgeTerminal , which enable presenting a trader's obligation as bi-directional positions like in MetaTrader 4. At the same time, the model underlying HedgeTerminal takes into account the character of the trading orders execution. That means that it can be successfully implemented both at the over-the-counter market FOREX and centralized exchanges like, for example, trading derivative securities in the derivatives section of Moscow Exchange.


HedgeTerminal is a fully featured trading terminal inside the MetaTrader 5 terminal. Through the mechanism of virtualization it changes the representation of the current positions so a trader or a trading robot can manage their individual trading positions. Neither the number of positions, nor their direction have any importance. I would like to place emphasis on the fact that we are talking about virtualization - a specific mechanism transforming the presentation of a trader's obligations but not their qualitative characteristics.


This is not about distorting the results of the trader's financial activity but about transforming representation of this activity. HedgeTerminal is based on the MetaTrader 5 trading environment and the MQL5 programming language. It does not bring new trading information to the terminal, it simply makes the current trading environment seen from a different angle. That means that HedgeTerminal is essentially MetaTrader 5 and is its native application. Even though, we could put an identity sign between them, an inclusion sign is more appropriate as HedgeTerminal is just a small and one of many MetaTrader 5 applications.


The virtualization possibility and the HedgeTerminal existence are based on three paradigms:


Conceptually, a complete and guaranteed convertibility of the position net representation into individual bi-directional trading transactions is possible . This statement proves the fact that in some external trading platforms including the ones designed for exchange trading, there is a means to manage bi-directional positions; The trading model of MetaTrader 5 at the user's level allows creating one way links of orders to each other . Calculations have shown that links designed in a certain way will be resistant to collisions. Moreover, even in the case of a corrupted history or any force majeure situations, bi-directional transactions could be retrospectively corrected and brought down to a financial result calculated at net representation; Advanced API in MQL5 allows to put the identity sign between MQL5 and the MetaTrader 5 terminal . In other words, nearly everything in MetaTrader 5 is accessible through the program interface and the MQL5 programming language. For instance, your own version of the terminal can be written inside the MetaTrader 5 terminal like HedgeTerminal.


This article discusses the underlying algorithms and how HedgeTerminal works. The specifications and algorithms ensuring consistent bi-directional trading are discussed in this article in detail. Irrespective of whether you decide to use HedgeTerminal or to create your own library to manage your own trading algorithms, you will find useful information in this article and its continuation.


This article is not targeting programmers specifically. If you do not have any experience in programming, you are still going to understand it. The MQL source code is not included in this article deliberately. All source code was replaced with more illustrative diagrams, tables and pictures schematically representing the operational principle and the data organization. I can tell from experience that even having a good grasp of programming principles, it is a lot easier to see a common pattern of the code than to analyze it.


In the second part of this article, we are going to talk about the integration of Expert Advisors with the HedgeTerminalAPI visualization library and then programming will be involved. However, even in that case, everything was done to simplify the perception of the code especially for novice programmers. For instance, object-oriented constructions like classes are not used though HedgeTerminal is an object oriented application.


How to Read this Article.


This article is rather lengthy. On the one hand, this is good as the answer to virtually any question regarding this topic can be found here. On the other hand, many users would prefer to read only the most important information returning to the relevant section whenever necessity arises. This article covers in full a consistent presentation of the material. Similar to books, we are going to give a short summary of every chapter so you can see whether you need to read it or not.


Part 1, Chapter 1. Theory of the bi-directional trading organization. This chapter contains the main ideas of HedgeTerminal. If you do not want in-depth information about organization of bi-directional trading, this chapter is sufficient to get an idea of the general principles of HedgeTerminal operation. This chapter is recommended for all readers.


I hope that this article is interesting enough so you read it up to the end.


Chapter 1. Organization theory of bi-directional trading.


1.1. MetaTrader 5 Opportunities in Organizing Bi-Directional Trading.


The article "Principles of Exchange Pricing through the Example of Moscow Exchange's Derivatives Market" carefully describes the nuances of the exchange price formation and methods of financial result calculation of the market players. It outlines that pricing and calculation on the Moscow Exchange significantly differ from concepts and calculation methods accepted in the FOREX trading.


On the whole, formation of the exchange price is more complex and contains a lot of significant details hidden when trading Forex and in the MetaTrader 4 terminal.


For example, in MetaTrader 4 the deals that executed the trader's order are hidden whereas in MetaTrader 5 such information is available. On the other hand, detailed trade information in MetaTrader 5 is not always required. It may make work difficult for an inexperienced user or a novice programmer and cause misunderstanding. For example, in MetaTrader 4, to find out the price of the executed order, you simple need to look up the correspondent value in the "Price" column. In the MQL4 programming language it is enough to call the OrderOpenPrice() function. In MetaTrader 5 it is required to find all the deals that executed the order and then go over them and calculate their weighted average price. This very price is the price of the order execution.


There are other situations when extended representation of the trading environment in MetaTrader 5 requires additional efforts to analyze this information. That prompts logical questions:


Is there a way of making the trading process in MetaTrader 5 as simple and clear as in MetaTrader 4 and keep a convenient access to all required trade details? If there is a way to arrange bi-directional exchange trading using MetaTrader 5 the same simple way as MetaTrader 4? - The answer to those questions is: "Yes, there is"!


Let us refer to the diagram of capabilities of the MetaTrader 4 and MetaTrader 5 terminals to understand how this is possible:


Fig. 1 Capabilities of MetaTrader 4 and MetaTrader 5.


As we can see, the "MetaTrader 5" set includes the "MetaTrader 4" subset. It means that everything possible in MetaTrader 4 can be done in MetaTrader 5 though the converse is false. New capabilities of MetaTrader 5 inevitably increase the amount and the complexity of the trade information presentation. This difficulty can be delegated to special assistant programs working in the MetaTrader 5 environment. These programs can process the complexity, leaving the terminal capabilities at the same level. One of such programs HedgeTerminal is the focus of this chapter.


HedgeTerminal is a full-fledged trading terminal inside the MetaTrader 5 terminal. It uses the MetaTrader 5 trading environment, transforms it with the MQL5 language and represents it as a convenient graphical interface - panel HedgeTerminalUltimate and special interface HedgeTerminalAPI for interaction with independent algorithms (Expert Advisors, scripts and indicators).


MetaTrader 4 features a possibility to use bi-directional positions or locking orders . In MetaTrader 5 there is such capability too but it is not explicit. This can be enabled using a specific add-on program, which HedgeTerminal essentially is. HedgeTerminal is built in MetaTrader 5 and uses its environment, gathering information by deals and orders into integrated positions looking very similar to orders in MetaTrader 4 and having all the capabilities of MetaTrader 5.


Such positions can be in a complete or partial locking order (when active long and short positions exist at the same time). The opportunity of maintaining such positions is not a goal in itself for HedgeTerminal. Its main objective is to unite trade information in unified groups (positions) that would be easy to analyze, manage and get access to. Bi-directional positions can exist in HedgeTerminal only because this is very convenient. In the case several traders are trading on one account, or more than one strategy is used, splitting trading actions must be arranged.


In addition, a number of nuances have to be taken into consideration at exchange trading such as partial order execution, position rollover, variation margin calculation, statistics and many others. HedgeTerminal was developed for meeting those challenges. It provides the user or an Expert Advisor a regular high level interface resembling MetaTrader 4 and at the same time working correctly in the exchange environment.


1.2. Pairing orders - Basis of Hedging and Statistics.


To be able to manage trading techniques and algorithms consistently, it is required to know with certainty what trading action belongs to what algorithm. I highlighted the words "with certainty" because if there is even the smallest probability of failure, crash of position management is inevitable sooner or later. In its turn, it will result in damage of statistics and undermining the idea of managing different algorithms on one account.


A reliable separation of trade activities is based on two fundamental possibilities:


The possibility of uniting or " pairing " two trading orders together so it can always be defined which of the two orders is opening the individual (virtual) position and which of them is closing this position; The algorithm, analyzing orders for their pairing must be completely deterministic and unified for all program modules.


The second requirement for the algorithm determinism will be considered in detail below. Now we are going to focus on the first one.


An order is an instruction to sell or buy. An order is a defined entity, which includes many more information "fields" in addition to the main information like magic number and order number, required price and opening conditions.


One of such fields in MetaTrader 5 is called " Order Magic ". This is a specified field used for a trading robot or an Expert Advisor to be able to mark this order with its individual unique number also called the "magic number". This field is not used in manual trade though it is very important for trading algorithms because when a trading algorithm analyses the values of this field, it can always see if the order in question was placed by it or any other algorithm.


Let us take a look at an example. Let us assume that we need to open a classical long position and then, in some time, close it. For that we have to place two orders. The first order will open this position and the second order will close it:


Fig. 2. Orders forming a historical net position.


What if we write the magic number of the first order in the field "Order Magic" of the second order at the moment of sending it to the market?


Later, this order's field can be read and if the value is equal to the number of the first order, then we can definitely say that the second order is related to the first one and is opposite to it, i. e. a closing order.


On a diagram this pairing would look like:


Fig. 3. Pairing orders.


Nominally such orders can be called paired as the second order contains a link to the first one. The first order opening a new position can be called an initiating or opening order. The second order can be called closing .


A pair of such orders can be called position . To avoid confusion with the concept of "position" in MetaTrader 5, we are going to call such paired positions bi-directional, hedging or the HedgeTerminal positions. Positions in MetaTrader 5 will be called net positions or the MetaTrader 5 classical positions.


Apparently, the number of HedgeTerminal positions and their directions, unlike the classical ones, can be any. What if there is an executed order that is not referred to by any other order? Such an order can be presented as an active bi-directional position. In fact, if an opposite order that contains a link to this order is placed, it will become an order that closes the first order. Such orders will become paired and make a closed bi-directional position as the volume of two orders is going to be equal and their direction is opposite.


So, let us define what is meant in HedgeTerminal by position:


If an executed order is not referred to by any other order, then HedgeTerminal treats such an order as an active bi-directional position .


If one executed order is referred to by another executed order, then two such orders make a pair and are treated by HedgeTerminal as one unified historical or closed bi-directional position.


In reality, pairing orders in HedgeTerminal is more complicated, as every order generates a minimum one deal and in exchange trade there can be many such deals. In general, the trade process can be presented as follows: a trader places an order to open a new position through the MetaTrader 5 terminal. The exchange executes this order through one or several deals.


Deals, similar to orders, contain fields for additional information. One of such fields contains the order id, on the basis of which the deal was executed. This field contains information about the order a certain deal belongs to. The converse is false. The order itself does not know what deals belong to it. It happens because at the time of placing the order it is not clear what deals will execute the order and if the order is going to be executed at all.


This way, causality or determinism of actions is observed. Deals are referring to orders and orders are referring to each other. Such a structure can be presented as a singly linked list.


Executed deals of the opening order generate a classical position in MetaTrader 5 and deals that belong to a closing order, on the contrary, close this position. These pairs are presented in the figure below:


Fig. 4. Diagram of a relationship between orders, deals and exchange.


We are going to get back to the detailed analysis of this diagram as the direction of the relationships is very important for building a strictly determined system of the trader's actions recording, which is HedgeTerminal.


1.3. Relationship of the MetaTrader 5 Net Positions and the HedgeTerminal Positions.


From the point of view of HedgeTerminal, two opposite orders with the same volumes can be two different positions. In this case their net position will be zero. That is why HedgeTerminal does not use information about the factual net positions opened in MetaTrader 5. Therefore, positions in HedgeTerminal are not connected with positions in MetaTrader 5 . The only time when the current net positions get verified is the moment of the HedgeTerminal launch. The total volumes of the opposite active positions must be identical to the values of the factual net positions.


If this is not the case, then a warning exclamation mark in a frame will appear on the HedgeTerminal, indicating that positions in HedgeTerminal and positions in MetaTrader 5 are not equal. This asymmetry does not affect the efficiency of HedgeTerminal, though for further correct work it has to be eliminated.


In the majority of cases, it can appear when users make errors editing the files of excluded orders ExcludeOrders. xml , though corruption of the order and deal history on the server can also cause this sign to emerge. In any case, these discrepancies can be removed by the exclusion mechanism implemented through the ExcludeOrders. xml file.


1.4. Requirements of the Algorithms Implementing Bi-Directional Trading.


Rather strict requirements are imposed on the algorithms implementing bi-directional trading. They must be met when developing HedgeTerminal. Otherwise, HedgeTerminal would quickly turn into a program working stochastically. The program would be "yet another solution that could operate or fail to do so with the same probability"


Below are some requirements specified for its development:


The representation of traders' bi-directional positions must be reliable. Any idea implemented in HedgeTerminal must not lead to ambiguity or potential errors in the business logic. If some property or opportunity does not meet these requirements, then this idea won't be used in spite of its convenience and the demand for it; All algorithms must be based on the MetaTrader 5 trading environment as much as possible. Storing additional information in the files is permitted in the cases when this is strictly necessary. The virtualization algorithms must receive the major part of information from the trading environment. This property enhances the total level of reliability as the majority of changes are conveyed through the server and therefore are accessible from any point in the world; All actions on the trading environment transformation must be performed behind the scenes. Complex configuration and initialization of the API HedgeTerminal library should not be required. A user should be able to launch the application "out of the box" and receive the expected result; The HedgeTerminal visual panel must fit the general MetaTrader 5 interface as seamlessly as possible, giving simple and understandable visual tools for work with bi-directional positions familiar to all the users of MetaTrader 4 and 5. In other words, the visual panel must be intuitively clear and simple for all users; The visual panel of HedgeTerminal must be designed taking into consideration algorithmic traders' high requirements. For instance, the panel must be configurable, the user must be able to change its appearance and even add custom modules; It must provide the Intuitive and simple program interface (API) of interactions with external Experts. The program part of interactions between external Experts and the HedgeTerminal algorithms must fit seamlessly the existing standard of the program interaction of the custom Experts with the MetaTrader 4/5 system functions. Actually, the HedgeTerminal API appears to be a hybrid of the MetaTrader 4 and MetaTrader 5 APIs; HedgeTerminal must ensure reliable work in the exchange environment, taking into account all the nuances of the exchange orders execution. HedgeTerminal is written based on the canonical article Principles of Exchange Pricing through the Example of Moscow Exchange's Derivatives Market". Initially, this article was a part of a long article about HedgeTerminal, which later was divided into several independent articles because of the volume. One can say that HedgeTerminal is a program implementation of the ideas discussed in this article.


Many of these ideas are not quite connected with each other. For instance, the abundance of the exchange information that is to be reflected in the exchange trading is difficult to connect with the simplicity of this information representation.


Another difficulty was to create a panel that could be easy to use for novice traders and at the same time provide extensive opportunities for professional algorithmic traders. Nevertheless, assessing the result, it is clear that these mutually exclusive properties were successfully implemented in HedgeTerminal.


Chapter 2. Installation of HedgeTerminal, First Launch.


2.1. Installation of HedgeTerminal.


We know that all executed orders in HedgeTerminal are considered as positions. Positions can consist either of two paired orders, which make a closed historical position or an unbound order, which makes an open or active position.


If before HedgeTerminal was installed, there were some actions on the trading account and the trading history contains a lot of executed orders, then from the point of view of HedgeTerminal all these orders will be open positions as the links between them were not created. It does not matter if the account history contains 2-3 executed orders. If there are thousands of them, HedgeTerminal will generate thousands of open positions. What can one do with them? These orders can be "closed" by placing opposite orders containing links to the initiating orders through HedgeTerminal. There is a down side though. If by the time of installing HedgeTerminal there are too many of them, it can ruin the trader as the brokerage fee and slippage expenses are to be paid.


To avoid this, HedgeTerminal launches a dedicated installation wizard at the beginning of its installation, where different solutions of this problem are suggested. Let us launch HedgeTerminal, call this wizard and describe its work in detail. For that download and install HedgeTerminalDemo from the MetaTrader 5 Market.


Similar to HedgeTerminalUltimate, it has a form of an Expert Advisor and all it takes to launch it is dragging its icon available in the "Navigator" folder to a free chart.


Dragging this icon will bring up a standard window suggesting to launch the Expert Advisor on the chart:


Fig. 5. The HedgeTerminal window before the launch.


At this stage it is enough to set the flag "Allow AutoTrading", allowing the EA to perform trade actions. HedgeTerminal will follow your orders as it does not have its own trading logic but for executing trades it will still need your permission.


For any Expert Advisor to start trading, the general permission for trading through Expert Advisors must be enabled on the panel in addition to the personal permission to trade in MetaTrader 5.


Fig. 6. Enabling automated trading.


HedgeTerminal was designed so the user could avoid long and complex configuration.


That is why all available settings are included in a special XML text file. The only explicit parameter for HedgeTerminal is the actual name of these settings file:


Fig. 7. Settings window of the HedgeTerminal panel.


The nature of these settings and the way to change them will be discussed later.


After pressing "OK", the HedgeTerminal installation wizard launches suggesting to start the installation process. The process of installation goes down to creating a few files in the shared directory for the terminals MetaTrader 4 and MetaTrader 5.


HedgeTerminal requests permission to install such files:


Fig. 8. Dialog of the installation start.


If you do not want some files to be installed on your computer, press "Cancel". In this case HedgeTerminal will finish work. To continue installation press "OK".


The appearance of the following dialog will depend on the account you launch HedgeTerminal with. If no trades were executed on the trading account, then HedgeTerminal will complete its work.


If some trades have already been executed, HedgeTerminal will display the following dialog:


Fig. 9. Dialog detecting the first launch of HedgeTerminal.


On the figure above, HedgeTerminal identified 5 active orders. In your case their number will be different (it is likely to be big and equal to the total number of executed orders of the account lifetime). These orders do not make a pair with a closing order as from the point of view of HedgeTerminal, they are active positions.


HedgeTerminal suggests several options.


Exclude these orders from HedgeTerminal: "You can hide them in HedgeTerminal. To hide these orders, click 'YES' and go into the next step" . If you choose this option and press "YES" , HedgeTerminal will put them into a specified list and from then will stop accounting their contribution to the aggregate net position as well as their financial result. These orders can be placed in the list only if there is no currently open net position. If you have an open position on one or several symbols, HedgeTerminal will call an additional dialog suggesting to close existing positions. Leave orders as they are and close them later if required: "You can… close manually later. Click 'No' if you want close these orders manually later. In this case, you have to perform 5 trades of opposite direction" . In this case, if you press "No" , HedgeTerminal will reflect after launch all these orders in the "Active" tab (i. e. as active positions). Later these orders can be closed with other orders through the HedgeTerminal panel. After that they will turn into closed positions and will be transferred to the "History" tab (historical positions). If these orders are great in number, then it is better to hide them than to close all executed orders again and pay brokerage fees. You can stop the installation: "If you are not ready continue press Cancel. In this case HedgeTerminal complete its work" . If you choose this option and press "Cancel", HedgeTerminal will stop its work.


If there are no active positions by the time HedgeTerminal is installed, installation will be stopped at this stage.


If you have selected the second option and you currently have one or several opened positions, HedgeTerminal will call an additional dialog suggesting to close them:


Fig. 10. Dialog suggesting to close net positions automatically.


HedgeTerminal requires closing all existing positions as all executed orders are to be put into the list of excluded orders. If there are no net positions, then any following order initializes a new net position. The direction and volume in this case are the same as in HedgeTerminal and that ensures avoiding unsynchronization of net positions with the total positions in HedgeTerminal.


HedgeTerminal can automatically close all net positions for you: "The HedgeTerminal can automatically close all active positions" . If this is acceptable to you, press "OK" . In this case it will try to close positions and if successful will finish work. If positions cannot be closed for some reason, it will move on to the dialog of manual position closing. If you select the manual position closing, "Click 'Cancel' if you want to close a position manually" , press "Cancel" .


The dialog of manual position closing is called either when manual closure type was chosen in the previous dialog window or when automatic position closure is impossible.


Fig. 11. Dialog suggesting to close net positions manually.


At this point all active positions have to be closed manually through MetaTrader 5 or installation should be cancelled by pressing "Cancel" . After all positions are closed, press "Retry" .


2.2. Three Step Installation. Installation Diagram and Solution to Possible Problems.


If we simplify the installation process as much as possible, it can be narrowed down to three steps:


Before installing HedgeTerminal, close all currently active net positions in the MetaTrader 5 terminal; Launch HedgeTerminal on the chart and press "Yes" in the appeared window of the installation wizard to start installation. HedgeTerminal in this case will install all the files required for its operation; In the next window if this appears, select the second option and press "Yes" . In this case active positions won't appear when HedgeTerminal is launched and the information about previously executed orders will be transferred to the ExcludeOrders. xml file automatically as there are no active positions requiring closure.


The simplest way to describe it is as follows: close all positions before launching Hedge Terminal and then press "Yes" two times in the HedgeTerminal installation wizard.


Complete pattern of the installation wizard is represented on the diagram below. It will help to answer the questions and perform installation correctly:


Fig. 12. Installation wizard.


What is the course of action if installation was not performed correctly or HedgeTerminal is required to be deleted from the computer? In the case installation was incorrect, simply delete all installed files. For that, go to the folder where programs for MetaTrader store shared information (as a rule this is located at: c:\Users\<your_user_name>\AppData\Roaming\MetaQuotes\Terminal\Common\Files\ ). If you want to delete information about the HedgeTerminal installation from all accounts, find the "HedgeTerminal" folder in this directory and delete it. If you want to delete information about the HedgeTerminal installation only for a certain account, go to the \HedgeTerminal\Brokers directory and select the folder, containing the name of your broker and the account number that looking like " Broker's name - account number ". Delete this folder. Next time the installation wizard will launch again when HedgeTerminal is started on this account.


Installation on the terminal connected to the account already working with HedgeTerminal. It may happen that that HedgeTerminal is required to be installed on the terminal connected to the account where HedgeTerminal is already working. As you already know, the installation process consists of creating and configuring system files. If all these files are already created on another computer and properly configured, then there is no need to install HedgeTerminal. As a rule, these files are stored at c:\Users\<your_user_name>\AppData\Roaming\MetaQuotes\Terminal\Common\Files\HedgeTerminal . Simply carry over this folder to the same place on your computer. After copying the directory, launch HedgeTerminal again. The installation wizard will not get called as all files are present and configured. In this case active positions will be similar to the display on other terminals and computers.


Installation of HedgeTerminalAPI and using the library in test mode. HedgeTerminal is implemented both as a visual panel and a library of program functions - HedgeTerminalAPI. The library contains a similar installation wizard called at the first launch of HedgeTerminalAPI in real time. Installing files when using the library is similar. At the first call of any function, the Expert will bring up a relevant MessageBox suggesting to start installation. In that case the user has to do the same thing - close all positions before calling HedgeTerminalAPI and perform installation in three steps.


It is not required to install HedgeTerminal when launching the library in test mode. As in test mode the Expert starts every time working with a new virtual account, there is no need to hide previously executed order and install files. The settings stored in the file Settings. xml , in the library can be defined grammatically through calling relevant functions.


2.3. Getting Started with HedgeTerminal, First Launch.


After HedgeTerminal has installed all the files required for its work, it will launch on the chart and display its panel:


Fig. 13. First launch of HedgeTerminal, appearance.


As all existing orders are hidden, there are no displayed active positions. The upper panel contains a button of the HedgeTerminal menu on the left hand side and dedicated icons displaying the state of the panel. The buttons have the following functions:


- Indicates that the panel demo version has been launched. This does not support the trade on real accounts and displays positions only on the AUDCAD and VTBR* symbols. In this mode, the history of positions is also limited by the last 10 closed positions. - Indicates that positions in HedgeTerminal are not equal to the total net position in MetaTrader 5. This is not a critical error but it is required to be eliminated. If the HedgeTerminal installation is correct, refer to the section of this article describing how to eliminate the mistake. - The icon signifies that trade is impossible. Hover the mouse over this icon and find out from the pop-up tip what the matter is. Possible reasons: no connection with the server; the Expert Advisor is prohibited to trade; trading with Expert Advisors is not allowed in MetaTrader 5. - An icon indicating that the trade is permitted; HedgeTerminal can perform any trade action.


Now, when HedgeTerminal is launched and ready for work, carry out several trades and see how they are displayed. If HedgeTerminal is launched on Forex, trading actions are to be executed on the AUDCAD symbol. Não deve haver nenhuma posição líquida aberta, pois a instalação do HedgeTerminal só poderia ser bem sucedida nesse caso. If this is not the case for some reason, close all active positions.


If HedgeTerminal is launched on an account connected to the Moscow Exchange, trading should be executed on one of the futures of the VTBR* group, for example VTBR-13.15 or VTBR-06.15. As an illustration, buy 0.4 lot of AUDCAD by the current price through the standard window "NewOrder". In a few moments, the order and the deal that executed it will appear in the order history of the terminal:


Fig. 14. Historical order and its deal in MetaTrader 5.


The active positions tab will contain a correspondent long position of 0.4 lot:


Fig. 15. Active net position in MetaTrader 5.


At the same time, HedgeTerminal will display the historical order as an active position:


Fig. 16. Active bi-directional position in HedgeTerminal and its deal.


As we can see, the results are the same, as one position in HedgeTerminal is correspondent to 1 net position in MetaTrader 5.


Please pay attention that in addition to the order, the position in HedgeTerminal contains a deal that executed this position (to see it, maximize the position string by pressing )


A part of an active position can be hidden. For that simply enter a new volume value in the field "Vol." (Volume). The new volume should be less than the current one. The difference between the current and the new volumes will be covered by the new order that forms a historical position and is displayed in the correspondent tab of historical positions. Enter the value of 0.2 in this field and then press Enter. In some time the volume of the active position is going to be 0.2 and the historical positions tab will feature the first historical transaction with the volume of 0.2 lot ( 0.4 - 0.2 = 0.2 ):


Fig. 17. Historical bi-directional position in HedgeTerminal.


In other words, we closed half of our active position. Common financial result of the historical and active position will be identical to the result in the terminal.


Now we are going to close the rest of the active position. For that press the button of closing a position in HedgeTerminal:


Fig. 18. Close button of a bi-directional position in HedgeTerminal.


After this button has been pressed, the remaining position must be closed by the opposite order and transferred to the historical position tab. This way active positions (both in MetaTrader 5 and in HedgeTerminal) will be closed.


2.4. Hedging and Calculation of Financial Operations.


In this section we are going to describe methods of work with HedgeTerminal using several bi-directional positions as an example.


So currently we do not have any active positions. Open a new long position with the volume of 0.2 lot on AUDCAD. For that it is enough to open the "new order" dialog window and place a correspondent order. After the position has been opened, lock it by the opposite position - sell 0.2 lot through the MetaTrader 5 terminal.


This time the trade result in HedgeTerminal and in the MetaTrader 5 terminal window are different. HedgeTerminal displays two positions:


Fig. 19. Opposite bi-directional positions in HedgeTerminal (lock)


In MetaTrader 5 they are not present at all:


Fig. 20. Absence of an active net position in MetaTrader 5.


Let us assess the result. 4 deals have been executed. They are in the red frame on the screenshot below:


Fig. 21. Result of executed deals in MetaTrader 5.


3 Ways Commodity Options Trading Differs from Stock Options.


I'm a huge fan of trading commodity options.


And you should be, too.


But there are some nuances when trading commodity options that you have to consider if you're going to move some capital away from equities.


These 3 differences are the most important concepts to understand, as they can potentially change the way you trade these instruments.


Fear is In Both Directions.


If there is one thing to learn about options is that each contract will have a different implied volatility. You can visualize implied volatility over various strikes by looking at the volatility skew.


Below is a picture from LiveVol showing the volatility skew for SPY June Options:


Notice that as we go lower in strike, the implied volatility on each contract rises. This is because option traders are willing to pay up for "tail-risk" protection, and most hedgers in equities are fearful of downside.


Compare that with the volatility skew for GLD June Options:


Instead of a "skew" we now have a "smile." What is going on here?


It comes down to the perception of risk . Equity investors are fearful of downside in equities. But in commodities like gold, oil, soybeans, and currencies the perception of risk is bi-directional.


That means the tail risk can be on either side.


Think about oil-- if we saw a $20 move in oil to the upside in a very short amount of time, that would have significant consequences across various assets.


So when hedgers and speculators come out to commodity options, they fear strong moves in either direction.


This changes the strategy set used in commodity options trading-- iron condors become more attractive, as do ratio sales after extreme moves.


Commodities Have Different Event Based Risk.


Single stock equities can be driven by upgrades, downgrades, earnings, FDA events, insider selling, holding updates, institutional rebalancing, intermarket correlation, same store sales. the list can keep going.


This heightened risk produces higher potential reward-- and for those that want to get more conservative, trading indexes or index futures can mitigate that risk.


With commodity options, the risks that drive movement are quite different than what drives equities. It could be based off supply reports or interest rate changes by central banks.


Because the risks are different, it can give you a way to diversify your trades against different risks. This can be crucial when finding the best trades.


Commodity Option Traders Are a Different Breed.


Remember, it comes down to the perception of risk.


Why is risk bi-directional?


Because the motivations in the commodities market are completely different than stocks.


Joe farmer needs to sell his soybeans. Spacely Sprocket company needs to hedge their Euro risk. ZeroHedge has to buy more silver to combat the manipulators.


Contrast that with stocks-- for 95% of the population, investing is the key term. They look to buy stock in companies.


Contrast that to gold and oil: there's no cash flow from these. From a structural standpoint, they aren't "investments."


Because the needs of these markets are different, the demands of these markets are different.


What's going on right now.


I see two possibilities heading into the summer months . Either event-based risk (Eurozone/China) makes a comeback or it doesn't. If we get the first scenario, then correlations will ratchet up among stocks and it will be a macro game again. If the second comes along, then summer volatility and liquidity in equities will dwindle.


Either way, commodity options trading is definitly coming back into my trading arsenal for the next few months.


Learn to Profitably Trade Iron Condors.


Want to beat the market without needing to time the market?


I've put together an Iron Condor Trading Toolkit that gives you the case studies and training needed to be consistently profitable in the market.


US Search Desktop.


Agradecemos seus comentários sobre como melhorar a Pesquisa do Yahoo. Este fórum é para você fazer sugestões de produtos e fornecer feedback atencioso. Estamos sempre tentando melhorar nossos produtos e podemos usar o feedback mais popular para fazer uma mudança positiva!


Se você precisar de assistência de qualquer tipo, visite nosso fórum de suporte à comunidade ou encontre ajuda individualizada em nosso site de ajuda. Este fórum não é monitorado por nenhum problema relacionado a suporte.


O fórum de comentários do produto do Yahoo agora exige um ID e uma senha válidos do Yahoo para participar.


Agora você precisa fazer login usando sua conta de e-mail do Yahoo para nos fornecer feedback e enviar votos e comentários para as ideias existentes. Se você não tiver um ID do Yahoo ou a senha do seu ID do Yahoo, inscreva-se para obter uma nova conta.


Se você tiver um ID e uma senha válidos do Yahoo, siga estas etapas se quiser remover suas postagens, comentários, votos e / ou perfil do fórum de comentários do produto do Yahoo.


Vote em uma ideia existente () ou publique uma nova ideia…


Idéias quentes Idéias superiores Novas ideias Categoria Status Meu feedback.


Trazer de volta o layout antigo com pesquisa de imagens.


Motor de busca no Yahoo Finance.


Um conteúdo que está no Yahoo Finance não aparece nos resultados de pesquisa do Yahoo ao pesquisar por título / título da matéria.


Existe uma razão para isso, ou uma maneira de reindexar?


Não consigo usar os idiomas ingleses no e-mail do Yahoo.


Por favor, me dê a sugestão sobre isso.


O que vocês pagam por boas sugestões que aumentam a receita porque eu tenho uma que é garantida para fazer $. Me avise se estiver interessado.


O que vocês pagam por boas sugestões que aumentam a receita porque eu tenho uma que é garantida para fazer $. Me avise se estiver interessado.


Por favor, envie para desindexação.


Por favor, envie o link '410' para desindexação. Obrigado.


diga trump a tempo de imposto todo o mundo doa 1 dólar como patos ilimitado e.


como eles fazem para patos ilimitados e os fundos quando eles correm para o escritório?


Pare de ser um traidor para o nosso país. Whoo nomeou você para ser Juiz e Júri re Trump.


Quem nomeou você como juiz e jurado do presidente Trump?


Não é fácil dar um comentário.


Mantenha a verdadeira notícia que é muito importante. Trunfos *** a vida antes de ele ser presidente não é importante hoje, quando ele nem estava no cargo. Rússia, China, militares, comércio, protegendo a fronteira que eu vivo precisando da parede etc é o que é importante. A mídia não achava que era importante quando outros presidentes estavam fazendo negócios enquanto estavam no cargo, como os Kennedy, Clinton e outros. Ele mostra que você está alvejando Trump, que não é isso que os relatórios devem fazer. Também você sabe que eu pareço lembrar quando Obama disse que ele usou o Facebook etc a máquina eletrônica para ajudá-lo a ser eleito e como eles eram espertos e eu pensei a mesma coisa, mas agora, quando é Trumps campanha usando isso que está errado. Você não consegue ver porque está perdendo os espectadores? Você não está sendo tarifa. Como sobre as coisas importantes nas notícias que afetam nossa segurança (defesa, proteção de nossas fronteiras, negócios para empregos, dinheiro em nossos livros de bolso, quem no congresso estava por trás deles recebendo um aumento, etc.) O que é coisas que queremos saber.


Mantenha a verdadeira notícia que é muito importante. Trunfos *** a vida antes de ele ser presidente não é importante hoje, quando ele nem estava no cargo. Rússia, China, militares, comércio, protegendo a fronteira que eu vivo precisando da parede etc é o que é importante. A mídia não achava que era importante quando outros presidentes estavam fazendo negócios enquanto estavam no cargo, como os Kennedy, Clinton e outros. Ele mostra que você está alvejando Trump, que não é isso que os relatórios devem fazer. Além disso, você sabe que eu me lembro quando Obama disse que ele usou o Facebook, etc o eletrônico ... mais.

Комментарии