Linguagem de programação do sistema de negociação


Linguagem de programação do sistema comercial.


Linguagem de programação do sistema comercial.


Linguagem de programação do sistema comercial.


Codificação de Sistemas de Negociação - Investopedia.


16.11.2018 & # 0183; & # 32; Vídeo embutido & # 0183; & # 32; - Instalando e configurando o idioma de programação R - Acessando o ambiente R do Seer - Incorporando o código R no Seer - Passando variáveis ​​e.


19. Idioma de programação de EasyLanguage - TradeStation & # 180; s para.


Você pode desenvolver sistema de negociação mecânica em linguagem de programação Java ou C # pura, enquanto outros idiomas ainda estão disponíveis para criar indicadores personalizados.


Estratégias de negociação automatizadas usando C # e NinjaTrader 7.


Quais linguagens de programação são mais utilizadas nas finanças quantitativas? dependendo de qual componente de um sistema de negociação você tenha a tarefa de construir.


Negociação algorítmica no Forex: crie seu primeiro - Udemy.


BJF Trading Group é forex Nós fornecemos o serviço de programação no MT4 MT4 / MT5 / JForex Expert Advisor ou o Forex Robot é um sistema de negociação de câmbio totalmente automatizado.


Linguagem de Programação - Quantopian.


Por Jacques Joubert. Nos últimos 6 meses, fiquei focado no processo de construção da pilha de tecnologia completa de um sistema de negociação automatizado.


Neural Trader Neural Network Programming Library | Módulo.


A maioria das estratégias algorítmicas são implementadas usando linguagens de programação modernas, um sistema de negociação algorítmico pode ser dividido em três partes.


Construindo Sistemas Automatizados de Negociação: Com uma Introdução.


Como um sistema de negociação algorítmico funcionará depende da linguagem de programação usada, e qual empregar realmente depende do que você está tentando alcançar.


As seis linguagens de programação mais populares para conhecer no setor bancário.


21.03.2007 & # 0183; & # 32; Building Automated Trading Systems: Com um Building Automated Trading Systems também # 20 em Books & gt; Computadores e Tecnologia & gt; Programação & gt; Línguas.


Metatrader Programming Services para Expert Advisors e.


Bill oferece programação de linguagem fácil para realmente aprender os prós e contras desta linguagem comercial. Todo o código do sistema é totalmente divulgado ao desenvolvedor.


Sistema automatizado de comércio cambial.


19.11.2018 & # 0183; & # 32; Forex Algorithmic Trading: uma linguagem de programação funcional usada pelo Meta Usando um sistema de negociação forex automatizado também remove um dos.


Inside Edge - Aprenda linguagem fácil.


TradeScript: uma nova e poderosa linguagem de programação vetorial para comerciantes para projetar sistemas de negociação sem experiência de programação prévia. O desenvolvimento de estratégias comerciais pode.


Modificando o sistema de negociação Easylanguage | Programação.


Melhor Linguagem de Programação para Sistemas de Negociação Algorítmica? Por Michael Halls-Moore em 26 de julho de 2018 Uma das perguntas mais frequentes que recebo no QS mailbag é.


Criando Sistemas Automatizados de Negociação Usando Interativo.


Automatizando a maneira como você comercializa Programando um Forex Com a linguagem de programação MQL4, o desempenho passado de qualquer sistema ou metodologia comercial não é.


Negociação algorítmica - Wikipedia.


Software de negociação MultiCharts para comerciantes profissionais com análise avançada, estratégias de negociação, backtesting e otimização. Plataforma de negociação que lhe dá uma vantagem.


Laboratório do Sistema de Negociação & # 174;


04.09.2018 & # 0183; & # 32; Criando Sistemas de Negociação Automatizados Usando Brokers Interativos: Introdução Criando Sistemas de Negociação Automatizados Usando Brokers Interativos: Por Precisão Automatizada.


Python Algorithmic Trading - Escolha preferida entre comerciantes.


O Laboratório de Sistema de Negociação não terá que aprender uma linguagem de programação. otimização que emprega o Algoritmo "Genético" menos poderoso. Genético.


Automatizando a maneira como você comercializa a programação de um robô Forex.


15.11.2017 & # 0183; & # 32; Sistemas operacionais; De outros ; Estratégias de negociação automatizadas usando C # e NinjaTrader 7 4.2 Compare com outros cursos de idiomas de programação.


O que as linguagens de programação são mais comumente usadas.


07.10.2004 & # 0183; & # 32; Até agora, discutimos os componentes básicos dos sistemas de negociação, os critérios que eles devem atender e algumas das muitas decisões empíricas que um sistema.


Sistemas de Negociação: Construindo um Sistema - Investopedia.


Codificação de sistemas de negociação Por aplicativo de software Justin ou um sistema de comércio, use a MetaQuotes II de MetaTrader para construir um modelo muito simples.


Laboratório de Sistema de Negociação: Introdução aos Programas Genéticos.


Mesmo o seu nome implica que é uma linguagem de programação para "não programadores". sistema de negociação automatizado (há linguagens de programação muito melhores,


Software Forex | MT4 Expert Advisors & amp; Indicadores | MQL4.


15.12.2018 & # 0183; & # 32; As seis linguagens de programação mais conhecidas em sistemas de negociação de alta freqüência ou baixa latência usam a linguagem de programação estatística R para.


TradeScript - A mais fácil programação de estratégia de negociação.


22.12.2018 & # 0183; & # 32; Por que o Python Algorithmic Trading é escolha preferida entre comerciantes? Para sobreviver na era dos robôs, é necessário aprender uma linguagem de programação que.


Forex & amp; CFD API | Negociação Automatizada | OANDA.


21.02.2018 & # 0183; & # 32; Criando sistemas de negociação automatizados na linguagem MQL4. Autorizado por Andrew R. Young, novo e totalmente atualizado para o mais recente.


Programação ProRealTime - Google+


EasyLanguage é uma linguagem de programação A popularidade deste idioma é tão difundida que pode ser considerada a linguagem de programação padrão na negociação.


Linguagem de Programação de Finanças Quantitativas - Stack Exchange.


17.11.2017 & # 0183; & # 32; Vídeo embutido & # 0183; & # 32; Trading With Forex Robots: Aprenda programação MQL4 Fazendo! Crie seu primeiro sistema de negociação algorítmica no MetaTrader 4.


Estratégias de negociação algorítmica Forex: minha experiência | Toptal.


07.09.2018 & # 0183; & # 32; Linguagens de programação para fundos de hedge de negociação, etc. e queria aprender algumas linguagens de programação, além de todos os C ++, se seu trabalho for construir sistemas,


Desenvolvimento do sistema comercial: negociação da faixa de abertura.


A biblioteca de programação pode ser usada para o sistema comercial que foi especialmente concebido para aplicações financeiras. uma variedade de linguagens de programação,


Treinamento e Tutoriais em Idiomas de Programação - Lynda.


Estratégias de negociação algorítmica - Esses sistemas de negociação automatizados simples tornarão seu investimento mais lucrativo. Use nosso sistema de negociação de futuros ou quantitativo.


A linguagem de programação mais fácil para comerciantes.


Apresentando o TradeScript, nossa nova e poderosa linguagem de programação que permite aos comerciantes projetar sistemas de negociação sem experiência de programação prévia.


Para quem é?


O TradeScript é um componente de desenvolvimento projetado para desenvolvedores de software que desejam expandir o conjunto de recursos em seu aplicativo comercial fornecendo uma linguagem de script.


O TradeScript, como idioma, destina-se a comerciantes que precisam escrever suas próprias estratégias comerciais, mas não sabem como programar em linguagens de baixo nível, como C e C ++.


O TradeScript permite que os comerciantes desenvolvam sistemas de negociação rápida e sem esforço. É tão fácil como 1-2-3.


Com o TradeScript, você pode habilitar seu aplicativo comercial para executar scripts que fornecem alertas quando o preço de uma segurança (estoque, futuros ou forex) alcança uma nova alta, cruza uma média móvel ou reduz uma porcentagem definida, embora essas sejam apenas alguns exemplos. O TradeScript também pode escanear o mercado, gerar sinais comerciais, estratégias de negociação de back-test e muito mais.


Linguagens de programação de vetores.


Aplicativos comerciais mais populares, como o MetaStock & trade ;, TradeStation & trade ;, NinjaTrader & trade ;, MetaTrader & trade; e outros fornecem suas próprias linguagens de programação (como MQL4, MQL5, EasyLanguage, linguagem de script do MetaStock, etc.). Sem uma linguagem de programação, os comerciantes não conseguem desenvolver sistemas de negociação automatizados ou realizar back-testing de estratégias.


Uma linguagem de programação vetorial oferece flexibilidade extrema com uma curva mínima de aprendizado. Na verdade, em apenas cinco minutos, você pode começar a escrever com o TradeScript.


Então, o que é uma linguagem de programação vetorial e por que é tão fácil de aprender?


As linguagens de programação de vetor (também conhecidas como matriz ou linguagens multidimensionais) generalizam operações em escalares para serem aplicadas de forma transparente para vetores, matrizes e matrizes dimensionais superiores. A idéia por trás da programação vetorial é que as operações se aplicam de uma só vez a um conjunto inteiro de valores (um vetor ou campo). Isso permite que você pense e opere em agregados inteiros de dados, sem recorrer a laços explícitos de operações escalares individuais.


Em outras palavras, é semelhante ao macro idioma encontrado no Excel.


A linguagem de programação mais fácil para os comerciantes. O mais poderoso também.


Um exemplo: para calcular uma média móvel simples com base no preço médio de uma garantia em 30 dias, em uma linguagem de programação tradicional, como o BASIC, você precisaria escrever um programa semelhante ao código mostrado neste bloco de código.


Várias linhas de código seriam necessárias para criar o vetor "MedianAmedes". Mas com o TradeScript, você pode realizar a mesma coisa usando apenas uma linha de código como mostrado abaixo.


Para n = barra - 30 a barra.


mediana = (CLOSE + OPEN) / 2.


Média = Média + Média.


Médias médias (bar) = Média / 30.


E agora MedianAverage torna-se um novo vetor que contém a média móvel simples de 30 períodos do preço médio da segurança.


Não é incomum encontrar a linguagem de programação da matriz "one-liners" que requerem mais do que algumas páginas do código BASIC, Java ou C ++. O mesmo vale para a criação de sistemas de negociação para testes de volta e alertas comerciais.


O TradeScript foi originalmente projetado como uma linguagem de programação de alto desempenho para comerciantes de alta freqüência. Ele foi projetado para verificar mais de 100.000 ações com base em critérios técnicos complexos e retornar resultados instantâneos em menos de cinco milissegundos. Isso foi há mais de dez anos. Hoje é ainda mais rápido.


Voltar Testar estatísticas.


Além de um registro de comércio real, os resultados do teste de volta do TradeScript incluem mais de 24 resultados estatísticos: número total de negócios, número médio de negócios por período, número de negócios rentáveis, número de operações de perda, lucro total, perda total, lucro percentual, maior Lucro, maior perda, redução máxima, Drawdown máximo (Monte Carlo), índice mensal de valor agregado (VAMI), ROR mensal composto, desvio padrão, desvio padrão anualizado, desvio reverso, taxa de Sharpe, taxa Sharpe anual, razão Sortino, razão calmaria, e Sterling Ratio.


Solução de Desenvolvimento Rápido e Fácil.


Se você é um desenvolvedor de software, ficará surpreso ao saber que apenas leva cerca de 30 minutos para implementar o TradeScript em seu aplicativo comercial. O TradeScript vem com ajuda sensível ao contexto, e nosso Guia do Programador pode ser enviado com seu aplicativo. Adicionar um idioma de script ao seu aplicativo comercial não poderia ser mais fácil.


Comece com o TradeScript>


Implementação da plataforma de negociação M4.


O TradeScript é a linguagem de programação utilizada na nossa plataforma de negociação M4, onde executa negócios automatizados, processa alertas em tempo real, executa varreduras de estoque e sistemas de negociação de back-tests.


Disponível em C ++ e em versões C #.


O TradeScript está disponível em C ++ (x64 para melhor desempenho) e C # para desenvolver aplicativos da web. Ele vem com mais de 30 projetos de exemplo e suporte para desenvolvedores extensivos para ajudá-lo a implementar a biblioteca em seu projeto.


Cenários de desenvolvimento comuns.


O TradeScript é mais usado em um dos três cenários. Muitas vezes, é usado dentro de aplicativos de comércio de desktop, onde é incorporado no lado do cliente. Também é comumente usado no lado do servidor, onde executa estratégias para clientes finos, como aplicativos móveis e web. Outro cenário comum é onde o TradeScript é executado no lado do servidor, a fim de fornecer resultados de digitalização em tempo real para usuários da web e móveis.


Programação genética.


Um algoritmo genético pode ser integrado no TradeScript para criar um mecanismo autônomo de criação de sistemas comerciais. Verifique o nosso mecanismo de algoritmo genético Evo2, que vem com exemplos do TradeScript.


Estudo de caso.


O TradeScript é usado em várias aplicações comerciais populares, uma das quais é a plataforma WhenToTrade Cycles and Algorithm Gentic. O estudo de caso descreve como o TradeScript é implementado para realizar análise cíclica dos mercados.


O WhenToTrade Cycles e a GA Platform combinam análise técnica usando TradeScript e gráficos financeiros usando StockChartX com novos algoritmos para análise cíclica. A solução faz parte de um pacote de conhecimento completo e permite que os comerciantes apliquem as estratégias derivadas a todos os tipos de mercados e prazos.


Com o TradeScript, você pode:


Crie scripts automatizados de entrada de ordens Execute milhares de alertas simultâneas Crie testes de retorno e otimização de sistema de negociação Crie gráficos orientados por script e conselheiros especializados Obtenha resultados de fórmula em tempo real.


Por que escolher o módulo?


O Modulus é uma empresa de tecnologia financeira. Embora isso não pareça um diferencial real, é. Isso significa que nossas soluções são de nossos anos de experiência no setor de tecnologia financeira. Nossos produtos e serviços são fornecidos por desenvolvedores e engenheiros que possuem experiência de negociação de primeira mão. Todo mundo aqui no Modulus fala seu idioma.


Direitos autorais e cópia; 2002-2018 por Modulus Global, Inc., todos os direitos reservados.


QuantStart.


Junte-se ao portal de membros privados da Quantcademy que atende à comunidade de comerciantes de varejo de varejo em rápido crescimento. Você encontrará um grupo bem informado de mentalistas quant pronto para responder suas perguntas comerciais mais importantes.


Confira meu ebook sobre o comércio de quant, onde eu ensino você como criar estratégias de negociação sistemáticas lucrativas com ferramentas Python, desde o início.


Dê uma olhada no meu novo ebook sobre estratégias de negociação avançadas usando análise de séries temporais, aprendizado de máquina e estatísticas bayesianas, com Python e R.


Por Michael Halls-Moore em 26 de julho de 2018.


Uma das perguntas mais freqüentes que recebo no QS mailbag é "Qual é a melhor linguagem de programação para negociação algorítmica?". A resposta curta é que não existe um "melhor" idioma. Parâmetros de estratégia, desempenho, modularidade, desenvolvimento, resiliência e custo devem ser considerados. Este artigo descreve os componentes necessários de uma arquitetura de sistema de negociação algorítmica e como as decisões relativas à implementação afetam a escolha do idioma.


Em primeiro lugar, serão considerados os principais componentes de um sistema de negociação algorítmico, como ferramentas de pesquisa, otimizador de portfólio, gerenciador de riscos e motor de execução. Posteriormente, serão examinadas diferentes estratégias de negociação e como elas afetam o design do sistema. Em particular, a freqüência de negociação e o provável volume de negociação serão discutidos.


Uma vez que a estratégia de negociação foi selecionada, é necessário arquitetar todo o sistema. Isso inclui a escolha de hardware, o (s) sistema (s) operacional (is) e a resiliência do sistema contra eventos raros e potencialmente catastróficos. Enquanto a arquitetura está sendo considerada, deve-se ter em conta o desempenho, tanto para as ferramentas de pesquisa quanto para o ambiente de execução ao vivo.


Qual é o sistema de comércio tentando fazer?


Antes de decidir sobre o "melhor" idioma com o qual escrever um sistema de negociação automatizado, é necessário definir os requisitos. O sistema será puramente baseado em execução? O sistema exigirá um módulo de gerenciamento de risco ou construção de portfólio? O sistema exigirá um backtester de alto desempenho? Para a maioria das estratégias, o sistema comercial pode ser dividido em duas categorias: Pesquisa e geração de sinal.


A pesquisa está preocupada com a avaliação de um desempenho de estratégia em relação aos dados históricos. O processo de avaliação de uma estratégia de negociação em relação aos dados anteriores do mercado é conhecido como backtesting. O tamanho dos dados e a complexidade algorítmica terão um grande impacto na intensidade computacional do backtester. A velocidade da CPU e a concorrência são muitas vezes os fatores limitantes na otimização da velocidade de execução da pesquisa.


A geração de sinal está preocupada com a geração de um conjunto de sinais de negociação a partir de um algoritmo e envio de ordens para o mercado, geralmente através de uma corretora. Para determinadas estratégias, é necessário um alto nível de desempenho. As questões de E / S, como a largura de banda da rede e a latência, muitas vezes são fatores limitantes na otimização de sistemas de execução. Assim, a escolha de idiomas para cada componente de todo o seu sistema pode ser bastante diferente.


Tipo, Frequência e Volume de Estratégia.


O tipo de estratégia algorítmica empregada terá um impacto substancial no design do sistema. Será necessário considerar os mercados comercializados, a conectividade com os fornecedores de dados externos, a freqüência e o volume da estratégia, o trade-off entre facilidade de desenvolvimento e otimização de desempenho, bem como qualquer hardware personalizado, incluindo customizado servidores, GPUs ou FPGAs que possam ser necessários.


As opções de tecnologia para uma estratégia de ações de baixa freqüência dos EUA serão muito diferentes das de uma negociação de estratégias de arbitragem estatística de alta freqüência no mercado de futuros. Antes da escolha do idioma, muitos fornecedores de dados devem ser avaliados que pertencem à estratégia em questão.


Será necessário considerar a conectividade com o fornecedor, a estrutura de todas as APIs, a pontualidade dos dados, os requisitos de armazenamento e a resiliência em face de um fornecedor que está offline. Também é aconselhável possuir acesso rápido a vários fornecedores! Vários instrumentos têm todos os seus peculiaridades de armazenamento, exemplos dos quais incluem símbolos de ticker múltiplos para ações e datas de vencimento para futuros (sem mencionar nenhum dado OTC específico). Isso precisa ser incorporado ao design da plataforma.


A frequência da estratégia provavelmente será um dos maiores drivers de como a pilha de tecnologia será definida. Estratégias que empregam dados com mais freqüência do que minuciosamente ou em segundo lugar, exigem uma consideração significativa em relação ao desempenho.


Uma estratégia que excede as barras segundo (isto é, dados de marca) leva a um design orientado a desempenho como o principal requisito. Para estratégias de alta freqüência, uma quantidade substancial de dados do mercado precisará ser armazenada e avaliada. Software como HDF5 ou kdb + é comumente usado para essas funções.


Para processar os extensos volumes de dados necessários para aplicações HFT, um sistema de backtester e execução extensivamente otimizado deve ser usado. C / C ++ (possivelmente com algum montador) é provável para o candidato a linguagem mais forte. As estratégias de ultra-alta freqüência certamente exigirão hardware personalizado, como FPGAs, co-localização de troca e ajuste de interface de rede / kernal.


Sistemas de pesquisa.


Os sistemas de pesquisa geralmente envolvem uma mistura de desenvolvimento interativo e script automatizado. O primeiro geralmente ocorre dentro de um IDE, como Visual Studio, MatLab ou R Studio. O último envolve cálculos numéricos extensos em vários parâmetros e pontos de dados. Isso leva a uma escolha de idioma que fornece um ambiente direto para testar código, mas também fornece desempenho suficiente para avaliar estratégias em várias dimensões de parâmetros.


Os IDE típicos neste espaço incluem Microsoft Visual C ++ / C #, que contém extensos utilitários de depuração, recursos de conclusão de código (via "Intellisense") e visões gerais diretas de toda a pilha do projeto (via o banco de dados ORM, LINQ); MatLab, que é projetado para uma grande variedade de álgebras lineares numéricas e operações vetoriais, mas de uma forma de console interativo; R Studio, que envolve o console de linguagem estatística R em um IDE de pleno direito; Eclipse IDE para Linux Java e C ++; e IDE semi-proprietários, como Enthought Canopy para Python, que incluem bibliotecas de análise de dados, como NumPy, SciPy, scikit-learn e pandas em um único ambiente interativo (console).


Para backtesting numérico, todos os idiomas acima são adequados, embora não seja necessário utilizar uma GUI / IDE, pois o código será executado "em segundo plano". A principal consideração nesta fase é a velocidade de execução. Um idioma compilado (como C ++) geralmente é útil se as dimensões do parâmetro backtest forem grandes. Lembre-se de que é necessário desconfiar de tais sistemas se for esse o caso!


Idiomas interpretados, como Python, muitas vezes fazem uso de bibliotecas de alto desempenho, como NumPy / pandas para a etapa de teste, para manter um grau razoável de competitividade com equivalentes compilados. Em última análise, o idioma escolhido para o backtesting será determinado por necessidades algorítmicas específicas, bem como o intervalo de bibliotecas disponíveis no idioma (mais sobre isso abaixo). No entanto, o idioma utilizado para o backtester e os ambientes de pesquisa podem ser completamente independentes dos usados ​​na construção de portfólio, gerenciamento de riscos e componentes de execução, como será visto.


Construção de carteiras e gerenciamento de riscos.


A construção do portfólio e os componentes de gerenciamento de riscos são muitas vezes ignorados pelos comerciantes algorítmicos de varejo. Isso é quase sempre um erro. Essas ferramentas fornecem o mecanismo pelo qual o capital será preservado. Eles não só tentam aliviar o número de apostas "arriscadas", mas também minimizam o churn dos próprios negócios, reduzindo os custos de transação.


Versões sofisticadas desses componentes podem ter um efeito significativo na qualidade e consistência da lucratividade. É direto criar um estável de estratégias, pois o mecanismo de construção do portfólio e o gerenciador de riscos podem ser facilmente modificados para lidar com múltiplos sistemas. Assim, eles devem ser considerados componentes essenciais no início do projeto de um sistema de comércio algorítmico.


O trabalho do sistema de construção de carteiras é levar um conjunto de trades desejados e produzir o conjunto de negócios reais que minimizam o churn, manter exposições a vários fatores (como setores, classes de ativos, volatilidade, etc.) e otimizar a alocação de capital para vários estratégias em um portfólio.


A construção do portfólio geralmente se reduz a um problema de álgebra linear (como uma fatoração da matriz) e, portanto, o desempenho é altamente dependente da eficácia da implementação de álgebra linear numérica disponível. As bibliotecas comuns incluem uBLAS, LAPACK e NAG para C ++. O MatLab também possui operações de matriz amplamente otimizadas. Python utiliza NumPy / SciPy para tais cálculos. Um portfólio freqüentemente reequilibrado exigirá uma biblioteca de matriz compilada (e bem otimizada!) Para executar esta etapa, de modo a não engarrafar o sistema de comércio.


O gerenciamento de riscos é outra parte extremamente importante de um sistema de comércio algorítmico. O risco pode vir de várias formas: aumento da volatilidade (embora isso possa ser visto como desejável para certas estratégias!), Aumento de correlações entre classes de ativos, contraparte padrão, interrupções do servidor, eventos de "cisnes negros" e erros não detectados no código comercial, para nomear alguns.


Os componentes de gerenciamento de risco tentam antecipar os efeitos da volatilidade excessiva e a correlação entre as classes de ativos e seus efeitos (s) subsequentes sobre o capital de negociação. Muitas vezes isso se reduz a um conjunto de cálculos estatísticos, como Monte Carlo "testes de estresse". Isso é muito semelhante às necessidades computacionais de um mecanismo de preços de derivativos e, como tal, será vinculado à CPU. Essas simulações são altamente paralelizáveis ​​(veja abaixo) e, até certo ponto, é possível "lançar hardware no problema".


Sistemas de Execução.


O trabalho do sistema de execução é receber sinais de negociação filtrados dos componentes de construção de portfólio e gerenciamento de riscos e enviá-los para uma corretora ou outros meios de acesso ao mercado. Para a maioria das estratégias de negociação algorítmica de varejo, isso envolve uma conexão API ou FIX para uma corretora, como Interactive Brokers. As considerações primárias ao decidir sobre um idioma incluem a qualidade da API, a disponibilidade do idioma para uma API, a freqüência de execução e o deslizamento antecipado.


A "qualidade" da API refere-se ao quão bem documentado é, qual o tipo de desempenho que ele fornece, se ele precisa de um software autônomo para ser acessado ou se um gateway pode ser estabelecido de forma sem cabeça (ou seja, sem GUI). No caso dos Interactive Brokers, a ferramenta Trader WorkStation precisa ser executada em um ambiente GUI para acessar sua API. Uma vez, tive que instalar uma edição do Desktop Ubuntu em um servidor de nuvem da Amazon para acessar os corretores interativos de forma remota, apenas por esse motivo!


A maioria das APIs fornecerá uma interface C ++ e / ou Java. Geralmente, é de responsabilidade da comunidade desenvolver wrappers específicos do idioma para C #, Python, R, Excel e MatLab. Note-se que, com cada plugin adicional utilizado (especialmente os wrappers da API), há possibilidades de insetos no sistema. Sempre testar plugins desse tipo e garantir que eles sejam ativamente mantidos. Um indicador valioso é ver quantas novas atualizações de uma base de código foram feitas nos últimos meses.


A frequência de execução é de extrema importância no algoritmo de execução. Note que centenas de pedidos podem ser enviados a cada minuto e, como tal, o desempenho é crítico. Slippage será incorrido através de um sistema de execução mal executado e isso terá um impacto dramático sobre a rentabilidade.


Os idiomas estaticamente digitados (veja abaixo), como C ++ / Java, geralmente são ótimos para execução, mas há um trade-off em tempo de desenvolvimento, testes e facilidade de manutenção. Idiomas dinamicamente digitados, como Python e Perl, geralmente são geralmente "rápidos o suficiente". Certifique-se sempre de que os componentes foram projetados de forma modular (veja abaixo) para que eles possam ser "trocados" à medida que o sistema se reduz.


Processo de Planejamento e Desenvolvimento Arquitetônico.


Os componentes de um sistema de comércio, seus requisitos de freqüência e volume foram discutidos acima, mas a infraestrutura do sistema ainda não foi coberta. Aqueles que atuam como comerciante de varejo ou que trabalham em um fundo pequeno provavelmente estarão "vestindo muitos chapéus". Será necessário cobrir o modelo alfa, o gerenciamento de riscos e os parâmetros de execução, bem como a implementação final do sistema. Antes de aprofundar linguagens específicas, o design de uma arquitetura de sistema ideal será discutido.


Separação de preocupações.


Uma das decisões mais importantes que devem ser tomadas no início é como "separar as preocupações" de um sistema comercial. No desenvolvimento de software, isso significa essencialmente como dividir os diferentes aspectos do sistema de negociação em componentes modulares separados.


Ao expor as interfaces em cada um dos componentes, é fácil trocar partes do sistema por outras versões que ajudem o desempenho, confiabilidade ou manutenção, sem modificar nenhum código de dependência externo. Esta é a "melhor prática" para esses sistemas. Para estratégias em frequências mais baixas, tais práticas são aconselhadas. Para a negociação de alta freqüência, o livro de regras pode ser ignorado à custa de ajustar o sistema para ainda mais desempenho. Um sistema mais acoplado pode ser desejável.


Criar um mapa de componentes de um sistema de negociação algorítmico vale um artigo em si. No entanto, uma abordagem ótima é garantir que haja componentes separados para as entradas de dados de mercado históricos e em tempo real, armazenamento de dados, API de acesso a dados, backtester, parâmetros de estratégia, construção de portfólio, gerenciamento de riscos e sistemas de execução automatizada.


Por exemplo, se o armazenamento de dados em uso estiver atualmente com desempenho inferior, mesmo em níveis significativos de otimização, ele pode ser trocado com reescrituras mínimas para a ingesta de dados ou API de acesso a dados. Até o ponto em que o backtester e os componentes subsequentes estão em causa, não há diferença.


Outro benefício de componentes separados é que permite que uma variedade de linguagens de programação sejam usadas no sistema geral. Não é necessário restringir a um único idioma se o método de comunicação dos componentes for independente de linguagem. Este será o caso se estiverem se comunicando via TCP / IP, ZeroMQ ou algum outro protocolo independente de linguagem.


Como um exemplo concreto, considere o caso de um sistema de backtesting que está sendo escrito em C ++ para o desempenho do "crunching", enquanto o gerenciador de portfólio e os sistemas de execução são escritos em Python usando SciPy e IBPy.


Considerações sobre o desempenho.


O desempenho é uma consideração significativa para a maioria das estratégias comerciais. Para estratégias de maior freqüência, é o fator mais importante. O "Desempenho" cobre uma ampla gama de problemas, como velocidade de execução algorítmica, latência de rede, largura de banda, E / S de dados, simultaneidade / paralelismo e dimensionamento. Cada uma dessas áreas é coberta individualmente por grandes livros didáticos, portanto este artigo apenas arranhará a superfície de cada tópico. A escolha da arquitetura e da linguagem agora será discutida em termos de seus efeitos sobre o desempenho.


A sabedoria prevalecente, como afirmou Donald Knuth, um dos pais da Ciência da Computação, é que "a otimização prematura é a raiz de todo o mal". Este é quase sempre o caso - exceto quando se forma um algoritmo de negociação de alta freqüência! Para aqueles que estão interessados ​​em estratégias de baixa freqüência, uma abordagem comum é construir um sistema da maneira mais simples possível e apenas otimizar à medida que os estrangulamentos começam a aparecer.


Ferramentas de perfil são usadas para determinar onde surgem os estrangulamentos. Perfis podem ser feitos para todos os fatores listados acima, em um ambiente MS Windows ou Linux. Existem muitas ferramentas de sistema operacional e de idioma disponíveis para isso, bem como utilitários de terceiros. A escolha da linguagem agora será discutida no contexto da performance.


C ++, Java, Python, R e MatLab contêm bibliotecas de alto desempenho (como parte do padrão ou externo) para estrutura básica de dados e trabalho algorítmico. C ++ é fornecido com a Biblioteca de modelos padrão, enquanto o Python contém NumPy / SciPy. Tarefas matemáticas comuns são encontradas nessas bibliotecas e raramente é benéfico escrever uma nova implementação.


Uma exceção é se uma arquitetura de hardware altamente personalizada é necessária e um algoritmo está fazendo uso extensivo de extensões proprietárias (como caches personalizados). No entanto, muitas vezes a "reinvenção da roda" desperdiça o tempo que pode ser melhor gasto no desenvolvimento e otimização de outras partes da infra-estrutura de negociação. O tempo de desenvolvimento é extremamente precioso especialmente no contexto dos únicos desenvolvedores.


A latência é muitas vezes uma questão do sistema de execução, pois as ferramentas de pesquisa geralmente estão localizadas na mesma máquina. Para o primeiro, a latência pode ocorrer em vários pontos ao longo do caminho de execução. Os bancos de dados devem ser consultados (latência de disco / rede), os sinais devem ser gerados (sistema operacional, latência de mensagens do kernal), sinais comerciais enviados (latência NIC) e pedidos processados ​​(latência interna dos sistemas de troca).


Para operações de maior freqüência, é necessário familiarizar-se intimamente com a otimização do kernal, além de otimizar a transmissão da rede. Esta é uma área profunda e está significativamente além do escopo do artigo, mas se um algoritmo UHFT é desejado então esteja ciente da profundidade do conhecimento necessário!


O cache é muito útil no conjunto de ferramentas de um desenvolvedor de negócios quantitativo. O armazenamento em cache refere-se ao conceito de armazenar dados freqüentemente acessados ​​de uma maneira que permita um acesso de alto desempenho, em detrimento do potencial estancamento dos dados. Um caso de uso comum ocorre no desenvolvimento da web ao tirar dados de um banco de dados relacional com respaldo de disco e colocá-lo na memória. Quaisquer pedidos subseqüentes para os dados não precisam "acessar o banco de dados" e, portanto, os ganhos de desempenho podem ser significativos.


Para situações de negociação, o cache pode ser extremamente benéfico. Por exemplo, o estado atual de um portfólio de estratégia pode ser armazenado em um cache até ser reequilibrado, de modo que a lista não precisa ser regenerada em cada ciclo do algoritmo de negociação. Essa regeneração provavelmente será uma alta CPU ou operação de E / S de disco.


No entanto, o armazenamento em cache não está sem os seus próprios problemas. A regeneração de dados de cache de uma só vez, devido à natureza volátil do armazenamento de cache, pode colocar uma demanda significativa na infraestrutura. Outra questão é o empilhamento de cães, onde múltiplas gerações de uma nova cópia de cache são realizadas sob uma carga extremamente alta, o que leva a uma falha em cascata.


A alocação de memória dinâmica é uma operação cara na execução de software. Assim, é imperativo que os aplicativos de maior desempenho comercial sejam conscientes de como a memória está sendo alocada e desalocada durante o fluxo do programa. Novos padrões de linguagem, como Java, C # e Python, todos executam a coleta automática de lixo, que se refere à desalocação da memória alocada dinamicamente quando os objetos ficam fora do escopo.


A coleta de lixo é extremamente útil durante o desenvolvimento, pois reduz erros e ajuda a legibilidade. No entanto, muitas vezes é sub óptimo para certas estratégias de negociação de alta freqüência. A coleta de lixo personalizada é muitas vezes desejada para esses casos. Em Java, por exemplo, ao ajustar a configuração do coletor de lixo e do heap, é possível obter alto desempenho para as estratégias de HFT.


C ++ não fornece um coletor de lixo nativo e, portanto, é necessário lidar com toda a alocação / desalocação de memória como parte da implementação de um objeto. Embora potencialmente propenso a erros (potencialmente levando a ponteiros pendurados), é extremamente útil ter um controle fino de como os objetos aparecem no heap para determinadas aplicações. Ao escolher um idioma, certifique-se de estudar como funciona o coletor de lixo e se ele pode ser modificado para otimizar um caso de uso específico.


Muitas operações em sistemas de negociação algorítmica são favoráveis ​​à paralelização. Isso se refere ao conceito de realização de múltiplas operações programáticas ao mesmo tempo, ou seja, em "paralelo". Os algoritmos denominados "embarassingly paralelos" incluem etapas que podem ser computadas totalmente independentemente de outras etapas. Certas operações estatísticas, como as simulações de Monte Carlo, são um bom exemplo de algoritmos embarazosa paralelos, pois cada sorteio aleatório e subsequente operação do caminho podem ser computados sem o conhecimento de outros caminhos.


Outros algoritmos são apenas parcialmente paralelizados. As simulações de dinâmica de fluidos são um exemplo, onde o domínio da computação pode ser subdividido, mas, em última instância, esses domínios devem se comunicar entre si e, portanto, as operações são parcialmente seqüenciais. Os algoritmos paralisáveis ​​estão sujeitos à Lei de Amdahl, que fornece um limite superior teórico para o aumento de desempenho de um algoritmo paralelizado quando sujeito a processos separados em $ N $ (por exemplo, em um núcleo ou fio de CPU).


A paralelização tornou-se cada vez mais importante como um meio de otimização, uma vez que as velocidades do clock do processador estagnaram, já que os processadores mais novos contêm muitos núcleos com os quais realizar cálculos paralelos. O aumento do hardware de gráficos de consumo (predominantemente para videogames) levou ao desenvolvimento de Unidades de processamento gráfico (GPUs), que contém centenas de "núcleos" para operações altamente concorrentes. Tais GPUs são agora muito acessíveis. Os quadros de alto nível, como o CUDA da Nvidia, levaram a uma adoção generalizada na academia e nas finanças.


Esse hardware de GPU geralmente é apenas adequado para o aspecto de pesquisa de financiamento quantitativo, enquanto que outros equipamentos mais especializados (incluindo matrizes de portas programáveis ​​em campo - FPGAs) são usados ​​para (U) HFT. Atualmente, a maioria dos langauges modernos suporta um grau de concorrência / multithreading. Assim, é direto otimizar um backtester, pois todos os cálculos são geralmente independentes dos outros.


O dimensionamento em engenharia e operações de software refere-se à capacidade do sistema de lidar consistentemente com o aumento de cargas sob a forma de solicitações maiores, maior uso do processador e maior alocação de memória. Na negociação algorítmica, uma estratégia pode escalar se pode aceitar quantidades maiores de capital e ainda produzir retornos consistentes. A pilha de tecnologia de negociação escala se pode suportar maiores volumes de comércio e latência aumentada, sem bloqueio de estrangulamento.


Enquanto os sistemas devem ser projetados para dimensionar, muitas vezes é difícil prever de antemão, onde um gargalo irá ocorrer. O registro, o teste, o perfil e o monitoramento rigorosos ajudarão grandemente em permitir que um sistema seja dimensionado. As próprias línguas são muitas vezes descritas como "inesquecíveis". Isso geralmente é o resultado de uma informação errônea, e não de um fato difícil. É a pilha de tecnologia total que deve ser verificada quanto à escalabilidade, e não ao idioma. Claramente, certas línguas têm maior desempenho do que outras em casos de uso específicos, mas um idioma nunca é "melhor" do que outro em todos os sentidos.


Um meio de gerenciar a escala é separar as preocupações, como afirmado acima. A fim de introduzir ainda a capacidade de lidar com "picos" no sistema (ou seja, uma volatilidade súbita que desencadeia uma série de trades), é útil criar uma "arquitetura de filas de mensagens". Isso simplesmente significa colocar um sistema de fila de mensagens entre os componentes para que as ordens sejam "empilhadas" se um determinado componente não conseguir processar muitos pedidos.


Em vez de pedidos de perda, eles simplesmente são mantidos em uma pilha até que a mensagem seja tratada. Isso é particularmente útil para enviar trocas para um mecanismo de execução. Se o motor está sofrendo em latência intensa, ele irá fazer backup de trades. Uma fila entre o gerador de sinal comercial e a API de execução aliviará essa questão à custa de uma possível destruição comercial. Um bem respeitado corretor de fila de mensagens de código aberto é RabbitMQ.


Hardware e sistemas operacionais.


O hardware que executa sua estratégia pode ter um impacto significativo na rentabilidade do seu algoritmo. Esta não é uma questão restrita aos comerciantes de alta freqüência. Uma má escolha em hardware e sistema operacional pode levar a uma falha na máquina ou reiniciar no momento mais inoportuno. Assim, é necessário considerar onde sua candidatura irá residir. A escolha é geralmente entre uma máquina de mesa pessoal, um servidor remoto, um provedor de "nuvem" ou um servidor co-localizado em troca.


As máquinas de mesa são simples de instalar e administrar, especialmente com sistemas operacionais mais novos e amigáveis, como o Windows 7/8, o Mac OSX eo Ubuntu. Os sistemas de desktop possuem algumas desvantagens significativas, no entanto. O principal é que as versões dos sistemas operacionais projetados para máquinas de mesa provavelmente irão requerer reinicialização / remendo (e muitas vezes no pior dos tempos!). Eles também usam mais recursos computacionais pela virtude de exigir uma interface gráfica do usuário (GUI).


Utilizar hardware em um ambiente doméstico (ou escritório local) pode levar à conectividade com a internet e aos problemas de tempo de atividade. O principal benefício de um sistema de desktop é que a potência computacional significativa pode ser comprada pela fração do custo de um servidor dedicado remoto (ou sistema baseado em nuvem) de velocidade comparável.


Um servidor dedicado ou uma máquina baseada em nuvem, muitas vezes mais caro do que uma opção de desktop, permite uma infra-estrutura de redundância mais significativa, como backups automatizados de dados, a capacidade de garantir de forma mais direta o tempo de atividade e monitoramento remoto. Eles são mais difíceis de administrar, pois exigem a capacidade de usar recursos de logon remoto do sistema operacional.


No Windows, isto é geralmente através do GUI Remote Desktop Protocol (RDP). Em sistemas baseados em Unix, a linha de comando Secure SHell (SSH) é usada. A infraestrutura de servidor baseada em Unix é quase sempre baseada em linha de comando, o que imediatamente faz com que as ferramentas de programação baseadas em GUI (como MatLab ou Excel) sejam inutilizáveis.


Um servidor co-localizado, como a frase é usada nos mercados de capitais, é simplesmente um servidor dedicado que se encontra dentro de uma troca para reduzir a latência do algoritmo de negociação. Isso é absolutamente necessário para certas estratégias de negociação de alta freqüência, que dependem de baixa latência para gerar alfa.


O aspecto final para a escolha do hardware e a escolha da linguagem de programação é a independência da plataforma. Existe a necessidade do código para executar vários sistemas operacionais diferentes? O código foi projetado para ser executado em um tipo específico de arquitetura de processador, como o Intel x86 / x64 ou será possível executar em processadores RISC, como os fabricados pela ARM? Essas questões serão altamente dependentes da frequência e do tipo de estratégia implementada.


Resiliência e Testes.


Uma das melhores maneiras de perder muito dinheiro na negociação algorítmica é criar um sistema sem resiliência. Isso se refere à durabilidade do sistema quando sujeito a eventos raros, como falências de corretagem, volatilidade súbita em excesso, tempo de inatividade em toda a região para um provedor de servidor em nuvem ou a exclusão acidental de um banco de dados de negociação inteiro. Anos de lucro podem ser eliminados em segundos com uma arquitetura mal projetada. It is absolutely essential to consider issues such as debuggng, testing, logging, backups, high-availability and monitoring as core components of your system.


It is likely that in any reasonably complicated custom quantitative trading application at least 50% of development time will be spent on debugging, testing and maintenance.


Nearly all programming languages either ship with an associated debugger or possess well-respected third-party alternatives. In essence, a debugger allows execution of a program with insertion of arbitrary break points in the code path, which temporarily halt execution in order to investigate the state of the system. The main benefit of debugging is that it is possible to investigate the behaviour of code prior to a known crash point .


Debugging is an essential component in the toolbox for analysing programming errors. However, they are more widely used in compiled languages such as C++ or Java, as interpreted languages such as Python are often easier to debug due to fewer LOC and less verbose statements. Despite this tendency Python does ship with the pdb, which is a sophisticated debugging tool. The Microsoft Visual C++ IDE possesses extensive GUI debugging utilities, while for the command line Linux C++ programmer, the gdb debugger exists.


Testing in software development refers to the process of applying known parameters and results to specific functions, methods and objects within a codebase, in order to simulate behaviour and evaluate multiple code-paths, helping to ensure that a system behaves as it should. A more recent paradigm is known as Test Driven Development (TDD), where test code is developed against a specified interface with no implementation. Prior to the completion of the actual codebase all tests will fail. As code is written to "fill in the blanks", the tests will eventually all pass, at which point development should cease.


TDD requires extensive upfront specification design as well as a healthy degree of discipline in order to carry out successfully. In C++, Boost provides a unit testing framework. In Java, the JUnit library exists to fulfill the same purpose. Python also has the unittest module as part of the standard library. Many other languages possess unit testing frameworks and often there are multiple options.


In a production environment, sophisticated logging is absolutely essential. Logging refers to the process of outputting messages, with various degrees of severity, regarding execution behaviour of a system to a flat file or database. Logs are a "first line of attack" when hunting for unexpected program runtime behaviour. Unfortunately the shortcomings of a logging system tend only to be discovered after the fact! As with backups discussed below, a logging system should be given due consideration BEFORE a system is designed.


Both Microsoft Windows and Linux come with extensive system logging capability and programming languages tend to ship with standard logging libraries that cover most use cases. It is often wise to centralise logging information in order to analyse it at a later date, since it can often lead to ideas about improving performance or error reduction, which will almost certainly have a positive impact on your trading returns.


While logging of a system will provide information about what has transpired in the past, monitoring of an application will provide insight into what is happening right now . All aspects of the system should be considered for monitoring. System level metrics such as disk usage, available memory, network bandwidth and CPU usage provide basic load information.


Trading metrics such as abnormal prices/volume, sudden rapid drawdowns and account exposure for different sectors/markets should also be continuously monitored. Further, a threshold system should be instigated that provides notification when certain metrics are breached, elevating the notification method (email, SMS, automated phone call) depending upon the severity of the metric.


System monitoring is often the domain of the system administrator or operations manager. However, as a sole trading developer, these metrics must be established as part of the larger design. Many solutions for monitoring exist: proprietary, hosted and open source, which allow extensive customisation of metrics for a particular use case.


Backups and high availability should be prime concerns of a trading system. Consider the following two questions: 1) If an entire production database of market data and trading history was deleted (without backups) how would the research and execution algorithm be affected? 2) If the trading system suffers an outage for an extended period (with open positions) how would account equity and ongoing profitability be affected? The answers to both of these questions are often sobering!


It is imperative to put in place a system for backing up data and also for testing the restoration of such data. Many individuals do not test a restore strategy. If recovery from a crash has not been tested in a safe environment, what guarantees exist that restoration will be available at the worst possible moment?


Similarly, high availability needs to be "baked in from the start". Redundant infrastructure (even at additional expense) must always be considered, as the cost of downtime is likely to far outweigh the ongoing maintenance cost of such systems. I won't delve too deeply into this topic as it is a large area, but make sure it is one of the first considerations given to your trading system.


Choosing a Language.


Considerable detail has now been provided on the various factors that arise when developing a custom high-performance algorithmic trading system. The next stage is to discuss how programming languages are generally categorised.


Type Systems.


When choosing a language for a trading stack it is necessary to consider the type system . The languages which are of interest for algorithmic trading are either statically - or dynamically-typed . A statically-typed language performs checks of the types (e. g. integers, floats, custom classes etc) during the compilation process. Such languages include C++ and Java. A dynamically-typed language performs the majority of its type-checking at runtime. Such languages include Python, Perl and JavaScript.


For a highly numerical system such as an algorithmic trading engine, type-checking at compile time can be extremely beneficial, as it can eliminate many bugs that would otherwise lead to numerical errors. However, type-checking doesn't catch everything, and this is where exception handling comes in due to the necessity of having to handle unexpected operations. 'Dynamic' languages (i. e. those that are dynamically-typed) can often lead to run-time errors that would otherwise be caught with a compilation-time type-check. For this reason, the concept of TDD (see above) and unit testing arose which, when carried out correctly, often provides more safety than compile-time checking alone.


Another benefit of statically-typed languages is that the compiler is able to make many optimisations that are otherwise unavailable to the dynamically - typed language, simply because the type (and thus memory requirements) are known at compile-time. In fact, part of the inefficiency of many dynamically-typed languages stems from the fact that certain objects must be type-inspected at run-time and this carries a performance hit. Libraries for dynamic languages, such as NumPy/SciPy alleviate this issue due to enforcing a type within arrays.


Open Source or Proprietary?


One of the biggest choices available to an algorithmic trading developer is whether to use proprietary (commercial) or open source technologies. Existem vantagens e desvantagens para ambas as abordagens. It is necessary to consider how well a language is supported, the activity of the community surrounding a language, ease of installation and maintenance, quality of the documentation and any licensing/maintenance costs.


The Microsoft stack (including Visual C++, Visual C#) and MathWorks' MatLab are two of the larger proprietary choices for developing custom algorithmic trading software. Both tools have had significant "battle testing" in the financial space, with the former making up the predominant software stack for investment banking trading infrastructure and the latter being heavily used for quantitative trading research within investment funds.


Microsoft and MathWorks both provide extensive high quality documentation for their products. Further, the communities surrounding each tool are very large with active web forums for both. The software allows cohesive integration with multiple languages such as C++, C# and VB, as well as easy linkage to other Microsoft products such as the SQL Server database via LINQ. MatLab also has many plugins/libraries (some free, some commercial) for nearly any quantitative research domain.


There are also drawbacks. With either piece of software the costs are not insignificant for a lone trader (although Microsoft does provide entry-level version of Visual Studio for free). Microsoft tools "play well" with each other, but integrate less well with external code. Visual Studio must also be executed on Microsoft Windows, which is arguably far less performant than an equivalent Linux server which is optimally tuned.


MatLab also lacks a few key plugins such as a good wrapper around the Interactive Brokers API, one of the few brokers amenable to high-performance algorithmic trading. The main issue with proprietary products is the lack of availability of the source code. This means that if ultra performance is truly required, both of these tools will be far less attractive.


Open source tools have been industry grade for sometime. Much of the alternative asset space makes extensive use of open-source Linux, MySQL/PostgreSQL, Python, R, C++ and Java in high-performance production roles. However, they are far from restricted to this domain. Python and R, in particular, contain a wealth of extensive numerical libraries for performing nearly any type of data analysis imaginable, often at execution speeds comparable to compiled languages, with certain caveats.


The main benefit of using interpreted languages is the speed of development time. Python and R require far fewer lines of code (LOC) to achieve similar functionality, principally due to the extensive libraries. Further, they often allow interactive console based development, rapidly reducing the iterative development process.


Given that time as a developer is extremely valuable, and execution speed often less so (unless in the HFT space), it is worth giving extensive consideration to an open source technology stack. Python and R possess significant development communities and are extremely well supported, due to their popularity. Documentation is excellent and bugs (at least for core libraries) remain scarce.


Open source tools often suffer from a lack of a dedicated commercial support contract and run optimally on systems with less-forgiving user interfaces. A typical Linux server (such as Ubuntu) will often be fully command-line oriented. In addition, Python and R can be slow for certain execution tasks. There are mechanisms for integrating with C++ in order to improve execution speeds, but it requires some experience in multi-language programming.


While proprietary software is not immune from dependency/versioning issues it is far less common to have to deal with incorrect library versions in such environments. Open source operating systems such as Linux can be trickier to administer.


I will venture my personal opinion here and state that I build all of my trading tools with open source technologies. In particular I use: Ubuntu, MySQL, Python, C++ and R. The maturity, community size, ability to "dig deep" if problems occur and lower total cost ownership (TCO) far outweigh the simplicity of proprietary GUIs and easier installations. Having said that, Microsoft Visual Studio (especially for C++) is a fantastic Integrated Development Environment (IDE) which I would also highly recommend.


Batteries Included?


The header of this section refers to the "out of the box" capabilities of the language - what libraries does it contain and how good are they? This is where mature languages have an advantage over newer variants. C++, Java and Python all now possess extensive libraries for network programming, HTTP, operating system interaction, GUIs, regular expressions (regex), iteration and basic algorithms.


C++ is famed for its Standard Template Library (STL) which contains a wealth of high performance data structures and algorithms "for free". Python is known for being able to communicate with nearly any other type of system/protocol (especially the web), mostly through its own standard library. R has a wealth of statistical and econometric tools built in, while MatLab is extremely optimised for any numerical linear algebra code (which can be found in portfolio optimisation and derivatives pricing, for instance).


Outside of the standard libraries, C++ makes use of the Boost library, which fills in the "missing parts" of the standard library. In fact, many parts of Boost made it into the TR1 standard and subsequently are available in the C++11 spec, including native support for lambda expressions and concurrency.


Python has the high performance NumPy/SciPy/Pandas data analysis library combination, which has gained widespread acceptance for algorithmic trading research. Further, high-performance plugins exist for access to the main relational databases, such as MySQL++ (MySQL/C++), JDBC (Java/MatLab), MySQLdb (MySQL/Python) and psychopg2 (PostgreSQL/Python). Python can even communicate with R via the RPy plugin!


An often overlooked aspect of a trading system while in the initial research and design stage is the connectivity to a broker API. Most APIs natively support C++ and Java, but some also support C# and Python, either directly or with community-provided wrapper code to the C++ APIs. In particular, Interactive Brokers can be connected to via the IBPy plugin. If high-performance is required, brokerages will support the FIX protocol.


Conclusão.


As is now evident, the choice of programming language(s) for an algorithmic trading system is not straightforward and requires deep thought. The main considerations are performance, ease of development, resiliency and testing, separation of concerns, familiarity, maintenance, source code availability, licensing costs and maturity of libraries.


The benefit of a separated architecture is that it allows languages to be "plugged in" for different aspects of a trading stack, as and when requirements change. A trading system is an evolving tool and it is likely that any language choices will evolve along with it.


Apenas iniciando o comércio quantitativo?


3 razões para se inscrever para a lista de e-mails QuantStart:


1. Quant Trading Lessons.


Você terá acesso instantâneo a um curso de e-mail gratuito de 10 partes, repleto de sugestões e dicas para ajudá-lo a começar a negociação quantitativa!


2. Todo o conteúdo mais recente.


Todas as semanas, vou enviar-lhe um envoltório de todas as atividades no QuantStart para que você nunca mais perca uma postagem novamente.


Real, dicas de negociação viáveis, sem tonturas.


QuantStart.


Junte-se ao portal de membros privados da Quantcademy que atende à comunidade de comerciantes de varejo de varejo em rápido crescimento. Você encontrará um grupo bem informado de mentalistas quant pronto para responder suas perguntas comerciais mais importantes.


Confira meu ebook sobre o comércio de quant, onde eu ensino você como criar estratégias de negociação sistemáticas lucrativas com ferramentas Python, desde o início.


Dê uma olhada no meu novo ebook sobre estratégias de negociação avançadas usando análise de séries temporais, aprendizado de máquina e estatísticas bayesianas, com Python e R.


By Michael Halls-Moore on July 26th, 2018.


One of the most frequent questions I receive in the QS mailbag is "What is the best programming language for algorithmic trading?". The short answer is that there is no "best" language. Strategy parameters, performance, modularity, development, resiliency and cost must all be considered. This article will outline the necessary components of an algorithmic trading system architecture and how decisions regarding implementation affect the choice of language.


Firstly, the major components of an algorithmic trading system will be considered, such as the research tools, portfolio optimiser, risk manager and execution engine. Subsequently, different trading strategies will be examined and how they affect the design of the system. In particular the frequency of trading and the likely trading volume will both be discussed.


Once the trading strategy has been selected, it is necessary to architect the entire system. This includes choice of hardware, the operating system(s) and system resiliency against rare, potentially catastrophic events. While the architecture is being considered, due regard must be paid to performance - both to the research tools as well as the live execution environment.


What Is The Trading System Trying To Do?


Before deciding on the "best" language with which to write an automated trading system it is necessary to define the requirements. Is the system going to be purely execution based? Will the system require a risk management or portfolio construction module? Will the system require a high-performance backtester? For most strategies the trading system can be partitioned into two categories: Research and signal generation.


Research is concerned with evaluation of a strategy performance over historical data. The process of evaluating a trading strategy over prior market data is known as backtesting . The data size and algorithmic complexity will have a big impact on the computational intensity of the backtester. CPU speed and concurrency are often the limiting factors in optimising research execution speed.


Signal generation is concerned with generating a set of trading signals from an algorithm and sending such orders to the market, usually via a brokerage. For certain strategies a high level of performance is required. I/O issues such as network bandwidth and latency are often the limiting factor in optimising execution systems. Thus the choice of languages for each component of your entire system may be quite different.


Type, Frequency and Volume of Strategy.


The type of algorithmic strategy employed will have a substantial impact on the design of the system. It will be necessary to consider the markets being traded, the connectivity to external data vendors, the frequency and volume of the strategy, the trade-off between ease of development and performance optimisation, as well as any custom hardware, including co-located custom servers, GPUs or FPGAs that might be necessary.


The technology choices for a low-frequency US equities strategy will be vastly different from those of a high-frequency statistical arbitrage strategy trading on the futures market. Prior to the choice of language many data vendors must be evaluated that pertain to a the strategy at hand.


It will be necessary to consider connectivity to the vendor, structure of any APIs, timeliness of the data, storage requirements and resiliency in the face of a vendor going offline. It is also wise to possess rapid access to multiple vendors! Various instruments all have their own storage quirks, examples of which include multiple ticker symbols for equities and expiration dates for futures (not to mention any specific OTC data). This needs to be factored in to the platform design.


Frequency of strategy is likely to be one of the biggest drivers of how the technology stack will be defined. Strategies employing data more frequently than minutely or secondly bars require significant consideration with regards to performance.


A strategy exceeding secondly bars (i. e. tick data) leads to a performance driven design as the primary requirement. For high frequency strategies a substantial amount of market data will need to be stored and evaluated. Software such as HDF5 or kdb+ are commonly used for these roles.


In order to process the extensive volumes of data needed for HFT applications, an extensively optimised backtester and execution system must be used. C/C++ (possibly with some assembler) is likely to the strongest language candidate. Ultra-high frequency strategies will almost certainly require custom hardware such as FPGAs, exchange co-location and kernal/network interface tuning.


Research Systems.


Research systems typically involve a mixture of interactive development and automated scripting. The former often takes place within an IDE such as Visual Studio, MatLab or R Studio. The latter involves extensive numerical calculations over numerous parameters and data points. This leads to a language choice providing a straightforward environment to test code, but also provides sufficient performance to evaluate strategies over multiple parameter dimensions.


Typical IDEs in this space include Microsoft Visual C++/C#, which contains extensive debugging utilities, code completion capabilities (via "Intellisense") and straightforward overviews of the entire project stack (via the database ORM, LINQ); MatLab, which is designed for extensive numerical linear algebra and vectorised operations, but in an interactive console manner; R Studio, which wraps the R statistical language console in a fully-fledged IDE; Eclipse IDE for Linux Java and C++; and semi-proprietary IDEs such as Enthought Canopy for Python, which include data analysis libraries such as NumPy, SciPy, scikit-learn and pandas in a single interactive (console) environment.


For numerical backtesting, all of the above languages are suitable, although it is not necessary to utilise a GUI/IDE as the code will be executed "in the background". The prime consideration at this stage is that of execution speed. A compiled language (such as C++) is often useful if the backtesting parameter dimensions are large. Remember that it is necessary to be wary of such systems if that is the case!


Interpreted languages such as Python often make use of high-performance libraries such as NumPy/pandas for the backtesting step, in order to maintain a reasonable degree of competitiveness with compiled equivalents. Ultimately the language chosen for the backtesting will be determined by specific algorithmic needs as well as the range of libraries available in the language (more on that below). However, the language used for the backtester and research environments can be completely independent of those used in the portfolio construction, risk management and execution components, as will be seen.


Portfolio Construction and Risk Management.


The portfolio construction and risk management components are often overlooked by retail algorithmic traders. This is almost always a mistake. These tools provide the mechanism by which capital will be preserved. They not only attempt to alleviate the number of "risky" bets, but also minimise churn of the trades themselves, reducing transaction costs.


Sophisticated versions of these components can have a significant effect on the quality and consistentcy of profitability. It is straightforward to create a stable of strategies as the portfolio construction mechanism and risk manager can easily be modified to handle multiple systems. Thus they should be considered essential components at the outset of the design of an algorithmic trading system.


The job of the portfolio construction system is to take a set of desired trades and produce the set of actual trades that minimise churn, maintain exposures to various factors (such as sectors, asset classes, volatility etc) and optimise the allocation of capital to various strategies in a portfolio.


Portfolio construction often reduces to a linear algebra problem (such as a matrix factorisation) and hence performance is highly dependent upon the effectiveness of the numerical linear algebra implementation available. Common libraries include uBLAS, LAPACK and NAG for C++. MatLab also possesses extensively optimised matrix operations. Python utilises NumPy/SciPy for such computations. A frequently rebalanced portfolio will require a compiled (and well optimised!) matrix library to carry this step out, so as not to bottleneck the trading system.


Risk management is another extremely important part of an algorithmic trading system. Risk can come in many forms: Increased volatility (although this may be seen as desirable for certain strategies!), increased correlations between asset classes, counter-party default, server outages, "black swan" events and undetected bugs in the trading code, to name a few.


Risk management components try and anticipate the effects of excessive volatility and correlation between asset classes and their subsequent effect(s) on trading capital. Often this reduces to a set of statistical computations such as Monte Carlo "stress tests". This is very similar to the computational needs of a derivatives pricing engine and as such will be CPU-bound. These simulations are highly parallelisable (see below) and, to a certain degree, it is possible to "throw hardware at the problem".


Sistemas de Execução.


The job of the execution system is to receive filtered trading signals from the portfolio construction and risk management components and send them on to a brokerage or other means of market access. For the majority of retail algorithmic trading strategies this involves an API or FIX connection to a brokerage such as Interactive Brokers. The primary considerations when deciding upon a language include quality of the API, language-wrapper availability for an API, execution frequency and the anticipated slippage.


The "quality" of the API refers to how well documented it is, what sort of performance it provides, whether it needs standalone software to be accessed or whether a gateway can be established in a headless fashion (i. e. no GUI). In the case of Interactive Brokers, the Trader WorkStation tool needs to be running in a GUI environment in order to access their API. I once had to install a Desktop Ubuntu edition onto an Amazon cloud server to access Interactive Brokers remotely, purely for this reason!


Most APIs will provide a C++ and/or Java interface. It is usually up to the community to develop language-specific wrappers for C#, Python, R, Excel and MatLab. Note that with every additional plugin utilised (especially API wrappers) there is scope for bugs to creep into the system. Always test plugins of this sort and ensure they are actively maintained. A worthwhile gauge is to see how many new updates to a codebase have been made in recent months.


Execution frequency is of the utmost importance in the execution algorithm. Note that hundreds of orders may be sent every minute and as such performance is critical. Slippage will be incurred through a badly-performing execution system and this will have a dramatic impact on profitability.


Statically-typed languages (see below) such as C++/Java are generally optimal for execution but there is a trade-off in development time, testing and ease of maintenance. Dynamically-typed languages, such as Python and Perl are now generally "fast enough". Always make sure the components are designed in a modular fashion (see below) so that they can be "swapped out" out as the system scales.


Architectural Planning and Development Process.


The components of a trading system, its frequency and volume requirements have been discussed above, but system infrastructure has yet to be covered. Those acting as a retail trader or working in a small fund will likely be "wearing many hats". It will be necessary to be covering the alpha model, risk management and execution parameters, and also the final implementation of the system. Before delving into specific languages the design of an optimal system architecture will be discussed.


Separation of Concerns.


One of the most important decisions that must be made at the outset is how to "separate the concerns" of a trading system. In software development, this essentially means how to break up the different aspects of the trading system into separate modular components.


By exposing interfaces at each of the components it is easy to swap out parts of the system for other versions that aid performance, reliability or maintenance, without modifying any external dependency code. This is the "best practice" for such systems. For strategies at lower frequencies such practices are advised. For ultra high frequency trading the rulebook might have to be ignored at the expense of tweaking the system for even more performance. A more tightly coupled system may be desirable.


Creating a component map of an algorithmic trading system is worth an article in itself. However, an optimal approach is to make sure there are separate components for the historical and real-time market data inputs, data storage, data access API, backtester, strategy parameters, portfolio construction, risk management and automated execution systems.


For instance, if the data store being used is currently underperforming, even at significant levels of optimisation, it can be swapped out with minimal rewrites to the data ingestion or data access API. As far the as the backtester and subsequent components are concerned, there is no difference.


Another benefit of separated components is that it allows a variety of programming languages to be used in the overall system. There is no need to be restricted to a single language if the communication method of the components is language independent. This will be the case if they are communicating via TCP/IP, ZeroMQ or some other language-independent protocol.


As a concrete example, consider the case of a backtesting system being written in C++ for "number crunching" performance, while the portfolio manager and execution systems are written in Python using SciPy and IBPy.


Performance Considerations.


Performance is a significant consideration for most trading strategies. For higher frequency strategies it is the most important factor. "Performance" covers a wide range of issues, such as algorithmic execution speed, network latency, bandwidth, data I/O, concurrency/parallelism and scaling. Each of these areas are individually covered by large textbooks, so this article will only scratch the surface of each topic. Architecture and language choice will now be discussed in terms of their effects on performance.


The prevailing wisdom as stated by Donald Knuth, one of the fathers of Computer Science, is that "premature optimisation is the root of all evil". This is almost always the case - except when building a high frequency trading algorithm! For those who are interested in lower frequency strategies, a common approach is to build a system in the simplest way possible and only optimise as bottlenecks begin to appear.


Profiling tools are used to determine where bottlenecks arise. Profiles can be made for all of the factors listed above, either in a MS Windows or Linux environment. There are many operating system and language tools available to do so, as well as third party utilities. A escolha da linguagem agora será discutida no contexto da performance.


C++, Java, Python, R and MatLab all contain high-performance libraries (either as part of their standard or externally) for basic data structure and algorithmic work. C++ ships with the Standard Template Library, while Python contains NumPy/SciPy. Common mathematical tasks are to be found in these libraries and it is rarely beneficial to write a new implementation.


One exception is if highly customised hardware architecture is required and an algorithm is making extensive use of proprietary extensions (such as custom caches). However, often "reinvention of the wheel" wastes time that could be better spent developing and optimising other parts of the trading infrastructure. Development time is extremely precious especially in the context of sole developers.


Latency is often an issue of the execution system as the research tools are usually situated on the same machine. For the former, latency can occur at multiple points along the execution path. Databases must be consulted (disk/network latency), signals must be generated (operating syste, kernal messaging latency), trade signals sent (NIC latency) and orders processed (exchange systems internal latency).


For higher frequency operations it is necessary to become intimately familiar with kernal optimisation as well as optimisation of network transmission. This is a deep area and is significantly beyond the scope of the article but if an UHFT algorithm is desired then be aware of the depth of knowledge required!


Caching is very useful in the toolkit of a quantitative trading developer. Caching refers to the concept of storing frequently accessed data in a manner which allows higher-performance access, at the expense of potential staleness of the data. A common use case occurs in web development when taking data from a disk-backed relational database and putting it into memory. Any subsequent requests for the data do not have to "hit the database" and so performance gains can be significant.


For trading situations caching can be extremely beneficial. For instance, the current state of a strategy portfolio can be stored in a cache until it is rebalanced, such that the list doesn't need to be regenerated upon each loop of the trading algorithm. Such regeneration is likely to be a high CPU or disk I/O operation.


However, caching is not without its own issues. Regeneration of cache data all at once, due to the volatilie nature of cache storage, can place significant demand on infrastructure. Another issue is dog-piling , where multiple generations of a new cache copy are carried out under extremely high load, which leads to cascade failure.


Dynamic memory allocation is an expensive operation in software execution. Thus it is imperative for higher performance trading applications to be well-aware how memory is being allocated and deallocated during program flow. Newer language standards such as Java, C# and Python all perform automatic garbage collection , which refers to deallocation of dynamically allocated memory when objects go out of scope .


Garbage collection is extremely useful during development as it reduces errors and aids readability. However, it is often sub-optimal for certain high frequency trading strategies. Custom garbage collection is often desired for these cases. In Java, for instance, by tuning the garbage collector and heap configuration, it is possible to obtain high performance for HFT strategies.


C++ doesn't provide a native garbage collector and so it is necessary to handle all memory allocation/deallocation as part of an object's implementation. While potentially error prone (potentially leading to dangling pointers) it is extremely useful to have fine-grained control of how objects appear on the heap for certain applications. When choosing a language make sure to study how the garbage collector works and whether it can be modified to optimise for a particular use case.


Many operations in algorithmic trading systems are amenable to parallelisation . This refers to the concept of carrying out multiple programmatic operations at the same time, i. e in "parallel". So-called "embarassingly parallel" algorithms include steps that can be computed fully independently of other steps. Certain statistical operations, such as Monte Carlo simulations, are a good example of embarassingly parallel algorithms as each random draw and subsequent path operation can be computed without knowledge of other paths.


Other algorithms are only partially parallelisable. Fluid dynamics simulations are such an example, where the domain of computation can be subdivided, but ultimately these domains must communicate with each other and thus the operations are partially sequential. Parallelisable algorithms are subject to Amdahl's Law, which provides a theoretical upper limit to the performance increase of a parallelised algorithm when subject to $N$ separate processes (e. g. on a CPU core or thread ).


Parallelisation has become increasingly important as a means of optimisation since processor clock-speeds have stagnated, as newer processors contain many cores with which to perform parallel calculations. The rise of consumer graphics hardware (predominently for video games) has lead to the development of Graphical Processing Units (GPUs), which contain hundreds of "cores" for highly concurrent operations. Such GPUs are now very affordable. High-level frameworks, such as Nvidia's CUDA have lead to widespread adoption in academia and finance.


Such GPU hardware is generally only suitable for the research aspect of quantitative finance, whereas other more specialised hardware (including Field-Programmable Gate Arrays - FPGAs) are used for (U)HFT. Nowadays, most modern langauges support a degree of concurrency/multithreading. Thus it is straightforward to optimise a backtester, since all calculations are generally independent of the others.


Scaling in software engineering and operations refers to the ability of the system to handle consistently increasing loads in the form of greater requests, higher processor usage and more memory allocation. In algorithmic trading a strategy is able to scale if it can accept larger quantities of capital and still produce consistent returns. The trading technology stack scales if it can endure larger trade volumes and increased latency, without bottlenecking .


While systems must be designed to scale, it is often hard to predict beforehand where a bottleneck will occur. Rigourous logging, testing, profiling and monitoring will aid greatly in allowing a system to scale. Languages themselves are often described as "unscalable". This is usually the result of misinformation, rather than hard fact. It is the total technology stack that should be ascertained for scalability, not the language. Clearly certain languages have greater performance than others in particular use cases, but one language is never "better" than another in every sense.


One means of managing scale is to separate concerns, as stated above. In order to further introduce the ability to handle "spikes" in the system (i. e. sudden volatility which triggers a raft of trades), it is useful to create a "message queuing architecture". This simply means placing a message queue system between components so that orders are "stacked up" if a certain component is unable to process many requests.


Rather than requests being lost they are simply kept in a stack until the message is handled. This is particularly useful for sending trades to an execution engine. If the engine is suffering under heavy latency then it will back up trades. A queue between the trade signal generator and the execution API will alleviate this issue at the expense of potential trade slippage. A well-respected open source message queue broker is RabbitMQ.


Hardware and Operating Systems.


The hardware running your strategy can have a significant impact on the profitability of your algorithm. This is not an issue restricted to high frequency traders either. A poor choice in hardware and operating system can lead to a machine crash or reboot at the most inopportune moment. Thus it is necessary to consider where your application will reside. The choice is generally between a personal desktop machine, a remote server, a "cloud" provider or an exchange co-located server.


Desktop machines are simple to install and administer, especially with newer user friendly operating systems such as Windows 7/8, Mac OSX and Ubuntu. Desktop systems do possess some significant drawbacks, however. The foremost is that the versions of operating systems designed for desktop machines are likely to require reboots/patching (and often at the worst of times!). They also use up more computational resources by the virtue of requiring a graphical user interface (GUI).


Utilising hardware in a home (or local office) environment can lead to internet connectivity and power uptime problems. The main benefit of a desktop system is that significant computational horsepower can be purchased for the fraction of the cost of a remote dedicated server (or cloud based system) of comparable speed.


A dedicated server or cloud-based machine, while often more expensive than a desktop option, allows for more significant redundancy infrastructure, such as automated data backups, the ability to more straightforwardly ensure uptime and remote monitoring. They are harder to administer since they require the ability to use remote login capabilities of the operating system.


In Windows this is generally via the GUI Remote Desktop Protocol (RDP). In Unix-based systems the command-line Secure SHell (SSH) is used. Unix-based server infrastructure is almost always command-line based which immediately renders GUI-based programming tools (such as MatLab or Excel) to be unusable.


A co-located server, as the phrase is used in the capital markets, is simply a dedicated server that resides within an exchange in order to reduce latency of the trading algorithm. This is absolutely necessary for certain high frequency trading strategies, which rely on low latency in order to generate alpha.


The final aspect to hardware choice and the choice of programming language is platform-independence. Is there a need for the code to run across multiple different operating systems? Is the code designed to be run on a particular type of processor architecture, such as the Intel x86/x64 or will it be possible to execute on RISC processors such as those manufactured by ARM? These issues will be highly dependent upon the frequency and type of strategy being implemented.


Resilience and Testing.


One of the best ways to lose a lot of money on algorithmic trading is to create a system with no resiliency . This refers to the durability of the sytem when subject to rare events, such as brokerage bankruptcies, sudden excess volatility, region-wide downtime for a cloud server provider or the accidental deletion of an entire trading database. Years of profits can be eliminated within seconds with a poorly-designed architecture. It is absolutely essential to consider issues such as debuggng, testing, logging, backups, high-availability and monitoring as core components of your system.


It is likely that in any reasonably complicated custom quantitative trading application at least 50% of development time will be spent on debugging, testing and maintenance.


Nearly all programming languages either ship with an associated debugger or possess well-respected third-party alternatives. In essence, a debugger allows execution of a program with insertion of arbitrary break points in the code path, which temporarily halt execution in order to investigate the state of the system. The main benefit of debugging is that it is possible to investigate the behaviour of code prior to a known crash point .


Debugging is an essential component in the toolbox for analysing programming errors. However, they are more widely used in compiled languages such as C++ or Java, as interpreted languages such as Python are often easier to debug due to fewer LOC and less verbose statements. Despite this tendency Python does ship with the pdb, which is a sophisticated debugging tool. The Microsoft Visual C++ IDE possesses extensive GUI debugging utilities, while for the command line Linux C++ programmer, the gdb debugger exists.


Testing in software development refers to the process of applying known parameters and results to specific functions, methods and objects within a codebase, in order to simulate behaviour and evaluate multiple code-paths, helping to ensure that a system behaves as it should. A more recent paradigm is known as Test Driven Development (TDD), where test code is developed against a specified interface with no implementation. Prior to the completion of the actual codebase all tests will fail. As code is written to "fill in the blanks", the tests will eventually all pass, at which point development should cease.


TDD requires extensive upfront specification design as well as a healthy degree of discipline in order to carry out successfully. In C++, Boost provides a unit testing framework. In Java, the JUnit library exists to fulfill the same purpose. Python also has the unittest module as part of the standard library. Many other languages possess unit testing frameworks and often there are multiple options.


In a production environment, sophisticated logging is absolutely essential. Logging refers to the process of outputting messages, with various degrees of severity, regarding execution behaviour of a system to a flat file or database. Logs are a "first line of attack" when hunting for unexpected program runtime behaviour. Unfortunately the shortcomings of a logging system tend only to be discovered after the fact! As with backups discussed below, a logging system should be given due consideration BEFORE a system is designed.


Both Microsoft Windows and Linux come with extensive system logging capability and programming languages tend to ship with standard logging libraries that cover most use cases. It is often wise to centralise logging information in order to analyse it at a later date, since it can often lead to ideas about improving performance or error reduction, which will almost certainly have a positive impact on your trading returns.


While logging of a system will provide information about what has transpired in the past, monitoring of an application will provide insight into what is happening right now . All aspects of the system should be considered for monitoring. System level metrics such as disk usage, available memory, network bandwidth and CPU usage provide basic load information.


Trading metrics such as abnormal prices/volume, sudden rapid drawdowns and account exposure for different sectors/markets should also be continuously monitored. Further, a threshold system should be instigated that provides notification when certain metrics are breached, elevating the notification method (email, SMS, automated phone call) depending upon the severity of the metric.


System monitoring is often the domain of the system administrator or operations manager. However, as a sole trading developer, these metrics must be established as part of the larger design. Many solutions for monitoring exist: proprietary, hosted and open source, which allow extensive customisation of metrics for a particular use case.


Backups and high availability should be prime concerns of a trading system. Consider the following two questions: 1) If an entire production database of market data and trading history was deleted (without backups) how would the research and execution algorithm be affected? 2) If the trading system suffers an outage for an extended period (with open positions) how would account equity and ongoing profitability be affected? The answers to both of these questions are often sobering!


It is imperative to put in place a system for backing up data and also for testing the restoration of such data. Many individuals do not test a restore strategy. If recovery from a crash has not been tested in a safe environment, what guarantees exist that restoration will be available at the worst possible moment?


Similarly, high availability needs to be "baked in from the start". Redundant infrastructure (even at additional expense) must always be considered, as the cost of downtime is likely to far outweigh the ongoing maintenance cost of such systems. I won't delve too deeply into this topic as it is a large area, but make sure it is one of the first considerations given to your trading system.


Choosing a Language.


Considerable detail has now been provided on the various factors that arise when developing a custom high-performance algorithmic trading system. The next stage is to discuss how programming languages are generally categorised.


Type Systems.


When choosing a language for a trading stack it is necessary to consider the type system . The languages which are of interest for algorithmic trading are either statically - or dynamically-typed . A statically-typed language performs checks of the types (e. g. integers, floats, custom classes etc) during the compilation process. Such languages include C++ and Java. A dynamically-typed language performs the majority of its type-checking at runtime. Such languages include Python, Perl and JavaScript.


For a highly numerical system such as an algorithmic trading engine, type-checking at compile time can be extremely beneficial, as it can eliminate many bugs that would otherwise lead to numerical errors. However, type-checking doesn't catch everything, and this is where exception handling comes in due to the necessity of having to handle unexpected operations. 'Dynamic' languages (i. e. those that are dynamically-typed) can often lead to run-time errors that would otherwise be caught with a compilation-time type-check. For this reason, the concept of TDD (see above) and unit testing arose which, when carried out correctly, often provides more safety than compile-time checking alone.


Another benefit of statically-typed languages is that the compiler is able to make many optimisations that are otherwise unavailable to the dynamically - typed language, simply because the type (and thus memory requirements) are known at compile-time. In fact, part of the inefficiency of many dynamically-typed languages stems from the fact that certain objects must be type-inspected at run-time and this carries a performance hit. Libraries for dynamic languages, such as NumPy/SciPy alleviate this issue due to enforcing a type within arrays.


Open Source or Proprietary?


One of the biggest choices available to an algorithmic trading developer is whether to use proprietary (commercial) or open source technologies. Existem vantagens e desvantagens para ambas as abordagens. It is necessary to consider how well a language is supported, the activity of the community surrounding a language, ease of installation and maintenance, quality of the documentation and any licensing/maintenance costs.


The Microsoft stack (including Visual C++, Visual C#) and MathWorks' MatLab are two of the larger proprietary choices for developing custom algorithmic trading software. Both tools have had significant "battle testing" in the financial space, with the former making up the predominant software stack for investment banking trading infrastructure and the latter being heavily used for quantitative trading research within investment funds.


Microsoft and MathWorks both provide extensive high quality documentation for their products. Further, the communities surrounding each tool are very large with active web forums for both. The software allows cohesive integration with multiple languages such as C++, C# and VB, as well as easy linkage to other Microsoft products such as the SQL Server database via LINQ. MatLab also has many plugins/libraries (some free, some commercial) for nearly any quantitative research domain.


There are also drawbacks. With either piece of software the costs are not insignificant for a lone trader (although Microsoft does provide entry-level version of Visual Studio for free). Microsoft tools "play well" with each other, but integrate less well with external code. Visual Studio must also be executed on Microsoft Windows, which is arguably far less performant than an equivalent Linux server which is optimally tuned.


MatLab also lacks a few key plugins such as a good wrapper around the Interactive Brokers API, one of the few brokers amenable to high-performance algorithmic trading. The main issue with proprietary products is the lack of availability of the source code. This means that if ultra performance is truly required, both of these tools will be far less attractive.


Open source tools have been industry grade for sometime. Much of the alternative asset space makes extensive use of open-source Linux, MySQL/PostgreSQL, Python, R, C++ and Java in high-performance production roles. However, they are far from restricted to this domain. Python and R, in particular, contain a wealth of extensive numerical libraries for performing nearly any type of data analysis imaginable, often at execution speeds comparable to compiled languages, with certain caveats.


The main benefit of using interpreted languages is the speed of development time. Python and R require far fewer lines of code (LOC) to achieve similar functionality, principally due to the extensive libraries. Further, they often allow interactive console based development, rapidly reducing the iterative development process.


Given that time as a developer is extremely valuable, and execution speed often less so (unless in the HFT space), it is worth giving extensive consideration to an open source technology stack. Python and R possess significant development communities and are extremely well supported, due to their popularity. Documentation is excellent and bugs (at least for core libraries) remain scarce.


Open source tools often suffer from a lack of a dedicated commercial support contract and run optimally on systems with less-forgiving user interfaces. A typical Linux server (such as Ubuntu) will often be fully command-line oriented. In addition, Python and R can be slow for certain execution tasks. There are mechanisms for integrating with C++ in order to improve execution speeds, but it requires some experience in multi-language programming.


While proprietary software is not immune from dependency/versioning issues it is far less common to have to deal with incorrect library versions in such environments. Open source operating systems such as Linux can be trickier to administer.


I will venture my personal opinion here and state that I build all of my trading tools with open source technologies. In particular I use: Ubuntu, MySQL, Python, C++ and R. The maturity, community size, ability to "dig deep" if problems occur and lower total cost ownership (TCO) far outweigh the simplicity of proprietary GUIs and easier installations. Having said that, Microsoft Visual Studio (especially for C++) is a fantastic Integrated Development Environment (IDE) which I would also highly recommend.


Batteries Included?


The header of this section refers to the "out of the box" capabilities of the language - what libraries does it contain and how good are they? This is where mature languages have an advantage over newer variants. C++, Java and Python all now possess extensive libraries for network programming, HTTP, operating system interaction, GUIs, regular expressions (regex), iteration and basic algorithms.


C++ is famed for its Standard Template Library (STL) which contains a wealth of high performance data structures and algorithms "for free". Python is known for being able to communicate with nearly any other type of system/protocol (especially the web), mostly through its own standard library. R has a wealth of statistical and econometric tools built in, while MatLab is extremely optimised for any numerical linear algebra code (which can be found in portfolio optimisation and derivatives pricing, for instance).


Outside of the standard libraries, C++ makes use of the Boost library, which fills in the "missing parts" of the standard library. In fact, many parts of Boost made it into the TR1 standard and subsequently are available in the C++11 spec, including native support for lambda expressions and concurrency.


Python has the high performance NumPy/SciPy/Pandas data analysis library combination, which has gained widespread acceptance for algorithmic trading research. Further, high-performance plugins exist for access to the main relational databases, such as MySQL++ (MySQL/C++), JDBC (Java/MatLab), MySQLdb (MySQL/Python) and psychopg2 (PostgreSQL/Python). Python can even communicate with R via the RPy plugin!


An often overlooked aspect of a trading system while in the initial research and design stage is the connectivity to a broker API. Most APIs natively support C++ and Java, but some also support C# and Python, either directly or with community-provided wrapper code to the C++ APIs. In particular, Interactive Brokers can be connected to via the IBPy plugin. If high-performance is required, brokerages will support the FIX protocol.


Conclusão.


As is now evident, the choice of programming language(s) for an algorithmic trading system is not straightforward and requires deep thought. The main considerations are performance, ease of development, resiliency and testing, separation of concerns, familiarity, maintenance, source code availability, licensing costs and maturity of libraries.


The benefit of a separated architecture is that it allows languages to be "plugged in" for different aspects of a trading stack, as and when requirements change. A trading system is an evolving tool and it is likely that any language choices will evolve along with it.


Apenas iniciando o comércio quantitativo?


3 razões para se inscrever para a lista de e-mails QuantStart:


1. Quant Trading Lessons.


Você terá acesso instantâneo a um curso de e-mail gratuito de 10 partes, repleto de sugestões e dicas para ajudá-lo a começar a negociação quantitativa!


2. Todo o conteúdo mais recente.


Todas as semanas, vou enviar-lhe um envoltório de todas as atividades no QuantStart para que você nunca mais perca uma postagem novamente.


Real, dicas de negociação viáveis, sem tonturas.


The Best Programming Languages for Trading.


While designing the algorithm trading system the major components research tool, risk manager, execution Engine, and portfolios optimiser should be considered. There are different trading strategies except them which will greatly in designing of the system. Once you decide the trading strategy, then it becomes easy to architect the whole system. The trading system includes the selection of operating system, choice of hardware, resiliency against rare and potentially catastrophic events. Before considering the system architecture first consider the performance, research tools as well as live execution environment. You can hire freelancers who know about trading.


Before deciding which programming languages are the best for creating the trading system first define the requirements of the system. Decide whether your system is completely execution based? Is your system required risk management software? Do your system require high-performance back tester? The trading system has two type of research and signal generation. The research of the system is the process of evolution of strategy performance over historical data. Signal generation is the process which generates the set of trading signals from the algorithm and sends such it to the market through a brokerage. The strategy of the trading algorithm impacts the design of the system. It is necessary to consider the connectivity to external data vendors, and volume of the strategy while developing the traded system.


Best Programming Languages for Trading.


C# is a programming language which is developed by Microsoft framework. It is language mostly used for web development. C# and Java programming language has more similarity than the C++ programming language. You can use C# and Java for the same function in trading. It is the general purpose object-oriented programming language so this language performs a lot of functionality and developer can easily create the trading application using this language. Now C# is also used for developing mobile apps for iOS and Android.


C++ is a general-purpose object-oriented language that has an impact on other programming languages, and this programming language creates the tons of applications, drivers, and firmware, etc. The C++ plays an important role in developing the component of High - Frequency trading that are latency sensitive because it is most efficient at processing a high volume of data. The software of C++ is also used in a different business application and also used in the banks legacy systems. Developing the trading application in other language becomes difficult because these programming languages require a lot of resources; so many developers prefer the C++ programming language for creating the trading application.


Java is a high-level object-oriented programming language is used for creating the server side applications, video games, and mobile applications. This programming language mostly used for data modeling, simulations, and low latency execution. This programming language is used for developing the native Android apps and web-based application. It is popular language because of its simplicity and readability. It is the language compatible with any system hence the developer can easily modify the existing developed application with this language. It is the language which has established itself as one of the most influential and solid programming languages. You can hire freelancers who have knowledge and experience in Java programming language.


Python has general purpose programming language usage. It is slower programming language than C++ and C# but greatly used in quant trading because it is a high-level programming language. Python has a great framework so anyone can develop application easily using this language. Because of the Python’s high performing libraries, the research and prototyping are easy. It is beginner friendly language because of its simple syntax structure, so it is easier for traders to pick up. Because of its simple programming structure developer can easily express the concept in fewer lines. Once you become mastered in basic syntax of Python, then you can easily comfortable with this language.


R is a programming language primarily used in statics and data analytics. R provides extensive variety of statistics such as classical statistical tests, linear and nonlinear modelling, and time - series analysis, clustering and graphical techniques. Use any sample data, and any good trading algorithm needs to get tested. R programming language allows designing of programs that generate trading signals and maximise strategy returns. It is the open source programming language which compiles and run on a wide variety of UNIX platform and similar system. You can find freelance jobs online in R programming language.


In this article, you get information regarding the best programming language for trading. Before picking the proper programming language for trading, you have to put extra efforts, setting aside time every single day to learn and practice, and participating in problem-solving events. Above mentioned programming languages easily helps you for analysis for trading.

Comments