Wednesday 3 May 2017

Java Trading System Architecture



Bem-vindo ao Home do Sistema de Negociação Open Java O Open Trading System Java (OJTS) pretende ser uma infra-estrutura comum para desenvolver sistemas de negociação de ações. Consiste em quatro partes: a coleta de dados brutos através da internet, o reconhecimento de sinais de negociação, um módulo de visualização e módulos para conexão com as interfaces programáticas de plataformas de negociação como bancos. O objetivo dos projetos é fornecer uma autônoma pura Java (plataforma independente) infra-estrutura comum para os desenvolvedores de sistemas de negociação. Alguns dos aspectos que devem ser abordados são fornecer um esquema de banco de dados comum compatível com SQL92 para armazenar dados financeiros, interfaces Java comuns para como intercambiar dados entre diferentes módulos, visualização de dados financeiros brutos e sinais de negociação e vários outros aspectos comuns necessários para criar Um sistema de negociação final. Por causa do meu trabalho e família eu não encontrar o tempo para melhorar OJTS mais. Estou continuando a atualizar a seção de links abaixo que irá orientá-lo para projetos mais ativos java open source nessa área, no entanto. Na verdade, como consequência do meu interesse na dinâmica dos mercados de ações, comecei uma viagem para os detalhes mais profundos da economia nacional, a fim de compreender as taxas de câmbio. Este tópico finalmente me leva a um estudo mais aprofundado do dinheiro em si como a unidade métrica que usamos na economia para medir o valor, o sucesso ou a utilidade. Este tópico acabou por ser extremamente interessante, mas ao mesmo tempo, foi muito difícil encontrar qualquer informação sobre como funciona o nosso sistema monetário. Dê a volta e pergunte às pessoas de onde vem o dinheiro, quem o cria eo que determina seu valor. Você vai notar que mesmo as pessoas que têm um mestrado ou Phd. Em economia não conhecerão esses detalhes. Oh, sim, eles vão responder em alguns termos crípticos técnicos, mas eles não serão capazes de desenhar um diagrama simples que descreve o processo. H. G. Wells é relatado para ter dito: Escrever da moeda é reconhecido geralmente como uma prática objetable, de fato quase um indecente. Os editores irão implorar ao escritor quase com lágrimas que não escrevam sobre dinheiro, não porque seja um assunto desinteressante, mas porque sempre foi profundamente perturbador. Sugiro a qualquer pessoa que viva em uma sociedade democrática para ler sobre este tópico. Ela afeta nossas vidas todos os dias em uma extensão que não pode ser exagerada Na minha opinião, cada cidadão de um país democrático nesse mundo deve saber de onde está vindo o nosso dinheiro. Muito provável você veio a este Web site a fim procurar ferramentas que o ajudam em aumentar sua riqueza monetary. Para entender o dinheiro da unidade métrica (não importa se o dólar ou o euro) será um ingrediente importante em seu toolkit para fazer o dinheiro. Se você tem pouco tempo e só pode dar ao luxo de ler um único livro sobre esse assunto, então eu sugiro que você leia riqueza, riqueza virtual e dívida por Frederick Soddy. Eu era capaz de comprar uma cópia usada via Amazon para 23.48, mas existe também uma versão on-line. Você precisará do plugin DjVu para lê-lo. Este livro foi publicado originalmente em 1929, mas ainda descreve os fatos reais muito bem. Mesmo se eu não concordo com todas as conclusões de Frederick Soddy seu trabalho é agradavelmente pensado provocando e levará você a fazer as perguntas certas. Anunciou a suspensão do desenvolvimento ativo e acrescentou referências a informações sobre nossos sistemas monetários (DollarEuro). Adicionado uma seção de links para outros projetos interessantes do sistema de negociação java. Estou investigando sobre como fazer OJTS mais compatível com outros esforços do sistema de negociação java. Projeto de Documentação do Sistema de Investimento e Negociação a ser encontrado em ITSdoc. org. Há um novo wiki disponível em ITSdoc. org focalizando na distribuição do conhecimento no domínio de sistemas de investimento e de troca. A idéia por trás do ITSdoc. org é ter uma plataforma de colaboração semelhante à wikipedia ajudando a comunidade a compartilhar conhecimento. OpenJavaTradingSystem v0.13 lançado. Ontem eu publiquei a versão 0.13 da biblioteca OpenJavaTradingSystem. Entre os novos recursos estão: Recuperação de dados para ações, fundos e moedas da OnVista. Implementação do tratamento de moeda e conversões. Os portfólios são implementados e você pode trabalhar com portfólios da mesma forma que com itens de papel de segurança simples. Foi adicionado um quadro geral para aplicação de algoritmos às séries temporais do mercado de ações. Mudou do shell interativo SISCScheme para ABCLCommonLisp mais seu editor chamado J. Adicionado um mecanismo de cache de dados gerais para armazenar em cache dados que já foram recuperados na web no sistema de arquivos. Além de muitas melhorias menores Se você está interessado nesta nova versão você deve começar na seção quickstartscreenshot. O manual ainda não está atualizado, mas pode fornecer algumas informações de fundo valiosas se você quiser usar a biblioteca em seu projeto. A documentação deve ser atualizada em breve. Atualmente não há muito desenvolvimento feito, porque estou atualizando meu conhecimento sobre as redes bayesianas. Veja, por exemplo, a lista de livros no meu site. Dois projetos muito interessantes a esse respeito são WEKA e BNJ. Logo vou continuar o desenvolvimento e vou começar a integrar a primeira inteligência no sistema. Hoje eu coloquei o primeiro lançamento na seção de arquivos da área de download sourceforge. Além disso atualizei o manual para documentar o uso interativo do projeto através da camada SISC Scheme. Para o impaciente aqui é uma seção quickstartscreenshot para você ir. Documentos que descrevem os aspectos internos do projeto. Documentação de Java Data Objects e Interface gtgtHTML gtgtPDF Documentação de Utilização gtgtHTML gtgtPDF Projecto de Documentação do Sistema de Investimento e Negociação gtgtITSdoc. org T echnology Blocos de Construção de Terceiros utilizados neste projecto HSQL Database Engine (licença: hsqldblic. txt) O HSQLDB é o motor de base de dados fornecido com o De modo que você pode começar imediatamente a usar o OJTS sem instalar um banco de dados de terceiros. Mas se você planeja usar outro banco de dados compatível com SQL92, então esta é uma opção de configuração. Castor (licença: A Licença Exolab) O Castor é uma estrutura de vinculação de dados Open Source para Javatm. É o caminho mais curto entre objetos Java, documentos XML e tabelas relacionais. O Castor fornece ligação Java-para-XML, persistência Java-to-SQL e muito mais. Castor Doclet (licença: GNU LGPL v2.1) Doclet Java para gerar arquivos de mapeamento e DDL para Castor JDO e Castor XML. TestMaker (licença: TestMaker Open-Source License) A partir do projeto TestMaker somente a implementação de protocolos como HTTP ou HTTPS são usados ​​para coletar dados da web. JCookie (licença: GNU LGPL v2.1) A biblioteca jCookie é necessária para que as bibliotecas do TestMaker funcionem. Htmlparser (licença: GNU LGPL v2.1) A biblioteca htmlparser é usada para extrair os dados dos recursos da web. ABCCLommonLisp (licença: GNU GPL v2) O ABCL (Armed Bear Common Lisp) é usado para implementar o coração algorítmico do projeto na linguagem de programação ANSI Common Lisp. JFreeChart (licença: GNU LGPL v2.1) O JFreeChart é usado para a visualização de dados financeiros como gráficos. JSci (licença: GNU LGPL v2.1) JSci - Uma API científica para Java. Joda Time (licença: Home-made OpenSource License) O Joda Time substitui as classes originais de Data e Hora do JDK. Links para outros projetos O grupo do JavaTraders do Google pode ser a melhor entrada para você saber mais sobre outros sistemas e ferramentas de negociação baseados em Java. L icense Termos de uso O código do projeto é licenciado sob os termos da LGPL e toda a documentação que você encontrar neste projeto são licenciados sob os termos da FDL. A Java Intra-dia Trading System Estas páginas web vêm de algum trabalho Eu fiz em um intra-day trading system, implementado em Java. Este software é executado sob o servidor de aplicativos Tomcat Java e suporta modelos de negociação que lêem um fluxo de dados de mercado em tempo real. Com base nesse fluxo de dados, o software gera ordens de compra e venda e rastreia sua posição no mercado. Por favor, não me envie e-mail perguntando quais técnicas de negociação vai fazer você rico. Eu sei muito sobre a implementação de sistemas de software complexos e eu sei algo sobre a construção de sistemas de negociação do mercado. Estou, no entanto, ainda trabalhando para uma vida assim que parece que eu não descobri o molho secreto mim. Eu não tenho qualquer mercado notável juju para transmitir a você. Sob certas condições, considerarei projetos de consultoria externos. Um projeto de consultoria deve ser aprovado pelo meu empregador, por isso há algumas despesas gerais no início (a última vez que fiz um desses projetos, levou um mês para obter aprovação). Só posso trabalhar com cidadãos americanos, cidadãos da Commonwealth britânica ou aliados da OTAN. A primeira regra para aqueles que trabalham para as taxas horárias é para ser pago, por isso não me escreva sugerindo que eu trabalho gratuitamente para uma participação no seu empreendimento. Eu sou um engenheiro de software muito experiente e cientista de computador e minhas taxas horárias refletem isso. Tradeengine. tar. gz Este é o sistema comercial que desenvolvi. Eu possuo os direitos de autor deste software e você não pode usá-lo para qualquer finalidade comercial sem permissão. Além disso, você não pode usar este software sem permissão para qualquer tipo de negociação no mercado. Uma vez que você não tem permissão para usar este software para qualquer outra coisa que não seja referência, você não pode me responsabilizar por qualquer erro neste software ou problemas encontrados em seu uso. Este software está ficando um pouco datado. Existem muitos recursos Java mais disponíveis agora. Embora isso mostre a arquitetura do núcleo, um sistema muito melhor poderia ser implementado usando recursos Java atuais. O sistema de negociação é projetado para trabalhar com o sistema Interactive Brokers trading através da interface Java. Estas páginas web consistem em notas sobre o design do sistema de comércio que desenvolvi. Há também notas sobre os experimentos com alguns estilos de análise técnica estilo intra-day trading. Um sistema de negociação Java é suportado por uma infra-estrutura de software complexa. Isso inclui o servidor web Apache Tomcat (servidor de aplicativos), feeds de dados em tempo real e software para suportar a interação baseada no navegador da Web com o usuário. Ao pesquisar o software que eu precisaria para apoiar o sistema de comércio, eu criei essas notas. Ian Kaplan janeiro de 2009 Última atualização em novembro de 2011Best Linguagem de Programação para Algorithmic Trading Systems Uma das perguntas mais freqüentes que recebo no mailbag QS é Qual é a melhor linguagem de programação para negociação algorítmica. A resposta curta é que não há melhor linguagem. Parâmetros de estratégia, desempenho, modularidade, desenvolvimento, resiliência e custo devem ser considerados. Este artigo descreverá 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 da linguagem. Em primeiro lugar, serão consideradas as principais componentes de um sistema de negociação algorítmica, tais como ferramentas de pesquisa, otimizador de portfólio, gerenciador de risco e mecanismo de execução. Posteriormente, diferentes estratégias de negociação serão examinadas e como elas afetam a concepção do sistema. Em particular, a frequência das negociações eo provável volume de transacções serão discutidos. Uma vez selecionada a estratégia de negociação, é necessário arquitetar todo o sistema. Isso inclui a escolha do hardware, do (s) sistema (s) operacional (is) e da resiliência do sistema contra eventos raros, potencialmente catastróficos. Enquanto a arquitetura está sendo considerada, devemos ter devidamente em conta o desempenho - tanto para as ferramentas de pesquisa como para o ambiente de execução ao vivo. O que é o sistema de negociação tentando fazer Antes de decidir sobre o melhor idioma com o qual escrever um sistema de negociação automatizado é necessário definir os requisitos. Será que o sistema vai ser puramente baseado em execução Será que o sistema exige uma gestão de risco ou módulo de construção de carteira Será que o sistema requer um backtester de alto desempenho Para a maioria das estratégias do sistema de negociação pode ser dividido em duas categorias: Pesquisa e geração de sinal. A pesquisa se preocupa com a avaliação do desempenho de uma estratégia em relação aos dados históricos. O processo de avaliação de uma estratégia de negociação sobre dados de mercado anteriores é conhecido como backtesting. O tamanho dos dados ea complexidade algorítmica terão um grande impacto na intensidade computacional do backtester. A velocidade ea simultaneidade da CPU são muitas vezes os fatores limitantes na otimização da velocidade de execução da pesquisa. Geração de sinal está preocupado com a geração de um conjunto de sinais de negociação a partir de um algoritmo e enviar tais ordens para o mercado, geralmente através de uma corretora. Para certas estratégias é necessário um alto nível de desempenho. As questões de E / S, como a largura de banda ea latência da rede, são freqüentemente o fator limitante na otimização de sistemas de execução. Assim, a escolha das linguagens para cada componente de todo o seu sistema pode ser bastante diferente. Tipo, Frequência e Volume da Estratégia O tipo de estratégia algorítmica empregada terá um impacto substancial na concepção do sistema. Será necessário considerar os mercados que estão sendo negociados, a conectividade com 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, Servidores, GPUs ou FPGAs que possam ser necessários. As escolhas tecnológicas para uma estratégia de ações de baixa freqüência nos EUA serão muito diferentes das de uma estratégia de arbitragem estatística de alta freqüência negociada no mercado de futuros. Antes da escolha da linguagem muitos fornecedores de dados devem ser avaliados que pertencem a uma estratégia em mãos. Será necessário considerar a conectividade com o fornecedor, a estrutura de qualquer API, a oportunidade dos dados, os requisitos de armazenamento e a resiliência em face de um fornecedor ficar offline. É também aconselhável possuir acesso rápido a vários fornecedores. Vários instrumentos têm todos os seus próprios caprichos de armazenamento, exemplos dos quais incluem múltiplos símbolos de ticker para ações e datas de vencimento para futuros (sem mencionar quaisquer dados OTC específicos). Isso precisa ser incorporado ao design da plataforma. Freqüência da estratégia é provável que seja um dos maiores drivers de como a pilha de tecnologia será definida. Estratégias empregando dados com mais freqüência do que minuciosamente ou barras de segunda necessidade significativa consideração no que diz respeito ao desempenho. Uma estratégia que ultrapassa as barras secundárias (isto é, dados de carraça) conduz a um design conduzido pelo desempenho como requisito primário. Para estratégias de alta freqüência, uma quantidade substancial de dados de mercado precisará ser armazenada e avaliada. Software como HDF5 ou kdb são comumente usados ​​para essas funções. Para processar os volumes extensos de dados necessários para aplicações HFT, um backtester extensivamente otimizado e sistema de execução deve ser usado. CC (possivelmente com algum montador) é provável que o candidato linguagem mais forte. As estratégias de freqüência ultra-alta quase certamente exigirão hardware personalizado, como FPGAs, troca de co-location e kernalnetwork interface tuning. Sistemas de pesquisa Os sistemas de pesquisa normalmente envolvem uma mistura de desenvolvimento interativo e scripts automatizados. O primeiro ocorre frequentemente dentro de um IDE, como Visual Studio, MatLab ou R Studio. Este último envolve cálculos numéricos extensos sobre vários parâmetros e pontos de dados. Isso leva a uma escolha de linguagem proporcionando um ambiente simples para testar o código, mas também fornece desempenho suficiente para avaliar estratégias em várias dimensões de parâmetro. IDEs típicos neste espaço incluem Microsoft Visual CC, que contém utilitários de depuração extensa, capacidades de conclusão de código (via Intellisense) e vistas gerais diretas de toda a pilha de projeto (via o banco de dados ORM, LINQ) MatLab. Que é projetado para a álgebra linear numerosa extensa e operações vectorized, mas em uma maneira console interativa R Studio. Que envolve o console de linguagem estatística R em um IDE Eclipse IDE totalmente desenvolvido para Linux Java e C e IDEs semi-proprietários, como o 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 GUIIDE como o código será executado em segundo plano. A principal consideração nesta fase é a da velocidade de execução. Uma linguagem compilada (como C) é frequentemente útil se as dimensões do parâmetro backtesting forem grandes. Lembre-se que é necessário ter cuidado com esses sistemas, se for esse o caso linguagens interpretadas como Python muitas vezes fazem uso de bibliotecas de alto desempenho, como NumPypandas para o backtesting passo, a fim de manter um grau razoável de competitividade com equivalentes compilados. Em última análise, o idioma escolhido para o backtesting será determinado por necessidades específicas algorítmicas, bem como a gama de bibliotecas disponíveis no idioma (mais sobre isso abaixo). No entanto, a linguagem utilizada para o backtester e ambientes de pesquisa pode ser completamente independente daqueles usados ​​nos componentes de construção de portfólio, gerenciamento de risco e execução, como veremos. Construção de Portfólio e Gerenciamento de Risco Os componentes de construção de carteira e gerenciamento de risco são freqüentemente ignorados por comerciantes de algoritmos 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 minimizar o churn das próprias operações, reduzindo os custos de transação. Versões sofisticadas desses componentes podem ter um efeito significativo na qualidade e consistência da lucratividade. É fácil criar um estável de estratégias como o mecanismo de construção de carteira e gerente de risco pode ser facilmente modificado para lidar com vários sistemas. Assim, eles devem ser considerados componentes essenciais no início do projeto de um sistema de negociação algorítmica. O trabalho do sistema de construção de carteira é levar um conjunto de negócios desejados e produzir o conjunto de negócios reais que minimizam 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 da carteira reduz-se frequentemente a um problema linear da álgebra (tal como uma factorização da matriz) e conseqüentemente o desempenho é altamente dependente da eficácia da execução numérica da álgebra linear disponível. As bibliotecas comuns incluem uBLAS. LAPACK e NAG para C. MatLab também possui operações de matriz amplamente otimizadas. Python utiliza NumPySciPy para tais computações. Uma carteira freqüentemente reequilibrada exigirá uma biblioteca de matriz compilada (e bem otimizada) para levar essa etapa para fora, de modo a não encolher o sistema de negociação. A gestão de risco é outra parte extremamente importante de um sistema de negociação algorítmica. 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, padrão de contraparte, interrupções de servidores, eventos de cisne preta e bugs não detectados no código de negociação poucos. Os componentes de gerenciamento de risco tentam antecipar os efeitos da volatilidade excessiva e correlação entre as classes de ativos e seus efeitos subseqüentes sobre o capital comercial. Muitas vezes isso se reduz a um conjunto de cálculos estatísticos, como testes de estresse de Monte Carlo. Isso é muito semelhante às necessidades computacionais de um mecanismo de determinação de preços de derivados e, como tal, será ligado à CPU. Essas simulações são altamente paralelas (ver 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 filtrada dos componentes de construção de carteira e gerenciamento de risco e enviá-los para uma corretora ou outros meios de acesso ao mercado. Para a maioria das estratégias de negociação de algoritmos de varejo, isso envolve uma conexão API ou FIX para uma corretora, como Interactive Brokers. As principais considerações ao decidir sobre uma linguagem incluem a qualidade da API, a disponibilidade do wrapper de linguagem para uma API, a freqüência de execução ea antecipação do deslizamento. A qualidade da API refere-se a quão bem documentada é, que tipo de desempenho fornece, se ele precisa de software autônomo para ser acessado ou se um gateway pode ser estabelecido de uma forma sem cabeça (ou seja, sem GUI). No caso de Interactive Brokers, a ferramenta Trader WorkStation precisa estar em execução em um ambiente GUI para acessar sua API. Uma vez eu tive que instalar uma edição Desktop Ubuntu em um servidor de nuvem Amazon para acessar Interactive Brokers remotamente, puramente por esta razão A maioria das APIs irá fornecer uma interface C andor Java. Normalmente, é a comunidade que desenvolve invólucros específicos de linguagem para C, Python, R, Excel e MatLab. Observe que com cada plugin adicional utilizado (especialmente API wrappers) há espaço para bugs a fluência no sistema. Sempre testar plugins desse tipo e garantir que eles sejam mantidos ativamente. Um indicador valioso é ver quantas novas atualizações de um codebase foram feitas nos últimos meses. A freqüência de execução é de extrema importância no algoritmo de execução. Observe 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 executando e isso terá um impacto dramático sobre a rentabilidade. Linguagens estaticamente tipadas (veja abaixo), como CJava, geralmente são ótimas para execução, mas há um trade-off no tempo de desenvolvimento, teste e facilidade de manutenção. As linguagens de tipo dinâmico, como Python e Perl, são agora geralmente suficientemente rápidas. Certifique-se sempre de que os componentes são projetados de forma modular (veja abaixo) para que possam ser trocados para fora à medida que o sistema é escalado. Processo de Planejamento e Desenvolvimento Arquitetônico Os componentes de um sistema de negociação, suas necessidades de freqüência e volume foram discutidos acima, mas a infra-estrutura do sistema ainda não foi coberta. Aqueles que atuam como um comerciante de varejo ou trabalhando em um pequeno fundo provavelmente será usando muitos chapéus. Será necessário estar cobrindo o modelo alfa, os parâmetros de gerenciamento e execução de riscos, e também a implementação final do sistema. Antes de aprofundar em linguagens específicas o projeto 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 de comércio. No desenvolvimento de software, isso significa essencialmente como quebrar os diferentes aspectos do sistema de comércio em componentes modulares separados. Ao expor as interfaces em cada um dos componentes, é fácil trocar partes do sistema por outras versões que auxiliem o desempenho, a confiabilidade ou a manutenção, sem modificar nenhum código de dependência externa. Esta é a melhor prática para esses sistemas. Para estratégias em freqüências mais baixas tais práticas são aconselhadas. Para a negociação de freqüência ultra alta o livro de regras pode ter que ser ignorado à custa de ajustar o sistema para ainda mais desempenho. Um sistema mais fortemente acoplado pode ser desejável. A criação de um mapa de componentes de um sistema de negociação algorítmico vale um artigo em si. No entanto, uma abordagem ótima é certificar-se de que há componentes separados para as entradas de dados históricos e em tempo real do mercado, 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 que está sendo usado está underperforming, até mesmo em níveis significativos de otimização, ele pode ser trocado com rewrites mínimo para a ingesta de dados ou API de acesso a dados. Tanto quanto o backtestter e componentes subsequentes estão em causa, não há diferença. Outro benefício de componentes separados é que ele permite que uma variedade de linguagens de programação para ser usado no sistema global. Não é necessário restringir-se a uma única língua se o método de comunicação dos componentes for independente da linguagem. Este será o caso se eles estão se comunicando via TCPIP, ZeroMQ ou algum outro protocolo independente de linguagem. Como exemplo concreto, considere o caso de um sistema de backtesting sendo escrito em C para o desempenho de crunching de números, enquanto o gerenciador de portfólio e sistemas de execução são escritos em Python usando SciPy e IBPy. Considerações sobre Desempenho O desempenho é uma consideração significativa para a maioria das estratégias de negociação. Para as estratégias de freqüência mais alta, é o fator mais importante. Desempenho cobre uma ampla gama de problemas, tais como velocidade de execução algorítmica, latência de rede, largura de banda, IO de dados, paralelismo de concorrência e dimensionamento. Cada uma dessas áreas são cobertas individualmente por grandes livros didáticos, portanto, este artigo apenas arranhará a superfície de cada tópico. A arquitetura ea escolha da língua serão agora discutidas em termos de seus efeitos sobre o desempenho. A sabedoria predominante como afirmado por Donald Knuth. Um dos pais da Ciência da Computação, é que a otimização prematura é a raiz de todo o mal. Isso é quase sempre o caso - exceto quando se constrói 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 como gargalos começam a aparecer. As ferramentas de criação de perfil são usadas para determinar onde surgem gargalos. Perfis podem ser feitos para todos os fatores listados acima, em um ambiente MS Windows ou Linux. Existem muitas ferramentas de sistema operacional e linguagem disponíveis para fazê-lo, bem como utilitários de terceiros. A escolha da língua será agora discutida no contexto do desempenho. C, Java, Python, R e MatLab contêm bibliotecas de alto desempenho (tanto como parte de seu padrão ou externamente) para estrutura de dados básicos e trabalho algorítmico. C é fornecido com a Biblioteca de modelos padrão, enquanto o Python contém NumPySciPy. Tarefas matemáticas comuns são encontradas nessas bibliotecas e raramente é benéfico escrever uma nova implementação. Uma exceção é se a 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 reinvenção da roda desperdiça tempo que poderia ser melhor gasto desenvolvendo e otimizando outras partes da infra-estrutura de negociação. Tempo de desenvolvimento é extremamente precioso, especialmente no contexto de desenvolvedores exclusivos. A latência é muitas vezes uma questão do sistema de execução, uma vez que as ferramentas de pesquisa estão normalmente situadas na mesma máquina. Para o primeiro, 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 disknetwork), sinais devem ser gerados (sistema operacional, latência de mensagens kernal), sinais de comércio enviados (latência NIC) e pedidos processados ​​(latência interna de sistemas de troca). Para operações de freqüência mais alta, é necessário tornar-se intimamente familiarizado com otimização kernal, bem como otimização da transmissão em rede. Esta é uma área profunda e está significativamente além do escopo do artigo, mas se um algoritmo UHFT é desejado, em seguida, estar ciente da profundidade do conhecimento necessário Caching é muito útil no kit de ferramentas de um desenvolvedor de negociação quantitativa. O cache refere-se ao conceito de armazenar dados acessados ​​com frequência de uma forma que permite um acesso de melhor desempenho, à custa da potencial indisponibilidade dos dados. Um caso de uso comum ocorre no desenvolvimento da web ao tirar dados de um banco de dados relacional com suporte a disco e colocá-lo na memória. Quaisquer solicitações subseqüentes para os dados não precisam acertar o banco de dados e, assim, os ganhos de desempenho podem ser significativos. Para situações de negociaçã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é que ele seja reequilibrado, de modo que a lista não precisa ser regenerada em cada loop do algoritmo de negociação. Tal regeneração é provável que seja uma CPU alta ou operação de E / S de disco. No entanto, o cache não é sem seus próprios problemas. A regeneração de dados de cache de uma só vez, devido à natureza volátil do armazenamento em cache, pode colocar uma demanda significativa na infra-estrutura. Outra questão é dog-piling. Onde várias gerações de uma nova cópia de cache são executadas sob carga extremamente alta, o que leva a uma falha em cascata. A alocação dinâmica de memória é uma operação cara na execução do software. Portanto, é imperativo que aplicativos de negociação de maior desempenho estejam bem conscientes de como a memória está sendo alocada e desalocada durante o fluxo do programa. Padrões de linguagem mais recentes, 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 saem do escopo. A coleta de lixo é extremamente útil durante o desenvolvimento, pois reduz os erros e facilita a legibilidade. No entanto, muitas vezes é sub-ideal para certas estratégias de negociação de alta freqüência. A coleta de lixo personalizada é freqüentemente desejada para esses casos. Em Java, por exemplo, ajustando o coletor de lixo ea configuração de heap, é possível obter alto desempenho para estratégias HFT. C não fornece um coletor de lixo nativo e, portanto, é necessário manipular toda a atribuição de alocação de memória como parte de uma implementação de objetos. Embora potencialmente propenso a erros (potencialmente levando a ponteiros pendentes) é extremamente útil ter controle de grão fino de como objetos aparecem no heap para determinadas aplicações. Ao escolher um idioma, certifique-se de estudar como o coletor de lixo funciona e se ele pode ser modificado para otimizar para um caso de uso particular. Muitas operações em sistemas de negociação algorítmicos são passíveis de paralelização. Isto refere-se ao conceito de realizar operações programáticas múltiplas ao mesmo tempo, isto é, em paralelo. Os chamados algoritmos embarassingly paralelos incluem etapas que podem ser calculadas de forma totalmente independente de outras etapas. Certas operações estatísticas, tais como simulações de Monte Carlo, são um bom exemplo de algoritmos embarassingly paralelos como cada desenho aleatório e operação de caminho subsequente pode ser computado sem o conhecimento de outros caminhos. Outros algoritmos são apenas parcialmente paralelizáveis. As simulações de dinâmica de fluidos são um exemplo, onde o domínio de computação pode ser subdividido, mas, em última instância, esses domínios devem se comunicar uns com os outros e, portanto, as operações são parcialmente sequenciais. Algoritmos paralelizáveis ​​estão sujeitos à Lei Amdahls. Que proporciona um limite superior teórico para o aumento de desempenho de um algoritmo paralelizado quando sujeito a N processos separados (por exemplo, num núcleo de CPU ou thread). 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, pois os processadores mais recentes contêm muitos núcleos com os quais realizar cálculos paralelos. A ascensão de hardware gráfico de consumo (predominantemente para jogos de vídeo) levou ao desenvolvimento de Unidades de Processamento Gráfico (GPUs), que contêm centenas de núcleos para operações altamente concorrentes. Essas GPUs são agora muito acessíveis. Estruturas de alto nível, como a Nvidias CUDA, têm levado à adoção generalizada na academia e nas finanças. Esse hardware GPU geralmente é adequado apenas para o aspecto de pesquisa de finanças quantitativas, enquanto outros hardware mais especializados (incluindo Field-Programmable Gate Arrays - FPGAs) são usados ​​para (U) HFT. Hoje em dia, a maioria dos langauges modernos suportam um grau de simultaneidademultithreading. Assim, é fácil otimizar um backtester, uma vez que todos os cálculos são geralmente independentes dos outros. Escala em engenharia de software e operações refere-se à capacidade do sistema para lidar consistentemente aumentando cargas na forma de solicitações maiores, maior uso do processador e mais alocação de memória. Na negociação algorítmica uma estratégia é capaz de escalar se ele pode aceitar grandes quantidades de capital e ainda produzir retornos consistentes. A pilha de tecnologia de negociação escalas se ele pode suportar maiores volumes de comércio e aumento da latência, sem gargalos. Enquanto os sistemas devem ser projetados para escalar, muitas vezes é difícil prever antecipadamente onde um gargalo irá ocorrer. Rigorosa exploração madeireira, testes, perfil e monitoramento vai ajudar muito em permitir que um sistema de escala. As próprias línguas são muitas vezes descritas como não escaláveis. Isso geralmente é o resultado de desinformação, ao invés de fato duro. É a pilha de tecnologia total que deve ser determinada para escalabilidade, não a linguagem. Claramente certas línguas têm um desempenho maior do que outras em casos de uso específicos, mas uma língua nunca é melhor que outra em todos os sentidos. Um meio de gerenciar a escala é separar preocupações, como mencionado acima. A fim de introduzir adicionalmente a capacidade de lidar com picos no sistema (isto é, volatilidade súbita que desencadeia uma série de negócios), é útil criar uma arquitectura de enfileiramento de mensagens. Isso significa simplesmente colocar um sistema de fila de mensagens entre componentes para que os pedidos sejam empilhados se um determinado componente não conseguir processar muitos pedidos. Ao invés de solicitações sendo perdidas eles são simplesmente mantidos em uma pilha até que a mensagem é tratada. Isso é particularmente útil para enviar comércios para um mecanismo de execução. Se o motor está sofrendo sob latência pesada, então ele vai fazer o backup de comércios. Uma fila entre o gerador de sinal de comércio e a API de execução aliviará esta questão à custa de uma potencial desvalorização do comércio. Um corretor de fila de mensagens de código aberto bem respeitado é RabbitMQ. Hardware e sistemas operacionais O hardware que executa sua estratégia pode ter um impacto significativo na rentabilidade do seu algoritmo. Este não é um problema restrito aos comerciantes de alta freqüência também. Uma má escolha em hardware e sistema operacional pode levar a uma máquina falhar ou reiniciar no momento mais inoportuno. Assim, é necessário considerar onde sua aplicação vai residir. A escolha é geralmente entre uma máquina desktop pessoal, um servidor remoto, um provedor de nuvem ou um servidor co-localizado de troca. As máquinas de mesa são simples de instalar e administrar, especialmente com os sistemas operacionais mais recentes, como o Windows 78, Mac OSX e Ubuntu. Os sistemas desktop possuem, no entanto, algumas desvantagens significativas. O principal é que as versões de sistemas operacionais projetados para máquinas desktop provavelmente exigirão rebootspatching (e muitas vezes no pior dos casos). Eles também usam mais recursos computacionais pela virtude de exigir uma interface gráfica com o usuário (GUI). A utilização de hardware em um ambiente doméstico (ou local) pode levar a conectividade com a internet e problemas de tempo de atividade. O principal benefício de um sistema desktop é que a potência computacional significativa pode ser comprada para a 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, embora muitas vezes mais cara do que uma opção de desktop, permite uma infra-estrutura de redundância mais significativa, como backups de dados automatizados, a capacidade de garantir mais facilmente o tempo de atividade e o monitoramento remoto. Eles são mais difíceis de administrar, pois requerem a capacidade de usar recursos de login remoto do sistema operacional. No Windows isso geralmente é via o GUI Remote Desktop Protocol (RDP). Nos 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 torna inutilizáveis ​​ferramentas de programação baseadas em GUI (como MatLab ou Excel). Um servidor co-localizado, como a frase é usada nos mercados de capital, é simplesmente um servidor dedicado que reside dentro de uma troca, a fim de reduzir a latência do algoritmo de negociação. 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 x86x64 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 pricesvolume, sudden rapid drawdowns and account exposure for different sectorsmarkets 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 wont 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 doesnt 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 NumPySciPy 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. There are advantages and disadvantages to both approaches. 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 licensingmaintenance 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 pluginslibraries (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, MySQLPostgreSQL, 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 dependencyversioning 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 systemprotocol (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 C11 spec, including native support for lambda expressions and concurrency. Python has the high performance NumPySciPyPandas 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 (MySQLC), JDBC (JavaMatLab), MySQLdb (MySQLPython) and psychopg2 (PostgreSQLPython). 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 . Conclusion 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. Just Getting Started with Quantitative TradingThe LMAX Architecture Over the last few years we keep hearing that the free lunch is over1 - we cant expect increases in individual CPU speed. So to write fast code we need to explicitly use multiple processors with concurrent software. This is not good news - writing concurrent code is very hard. Locks and semaphores are hard to reason about and hard to test - meaning we are spending more time worrying about satisfying the computer than we are solving the domain problem. Various concurrency models, such as Actors and Software Transactional Memory, aim to make this easier - but there is still a burden that introduces bugs and complexity. So I was fascinated to hear about a talk at QCon London in March last year from LMAX. LMAX is a new retail financial trading platform. Its business innovation is that it is a retail platform - allowing anyone to trade in a range of financial derivative products2. A trading platform like this needs very low latency - trades have to be processed quickly because the market is moving rapidly. A retail platform adds complexity because it has to do this for lots of people. So the result is more users, with lots of trades, all of which need to be processed quickly.3 Given the shift to multi-core thinking, this kind of demanding performance would naturally suggest an explicitly concurrent programming model - and indeed this was their starting point. But the thing that got peoples attention at QCon was that this wasnt where they ended up. In fact they ended up by doing all the business logic for their platform: all trades, from all customers, in all markets - on a single thread. A thread that will process 6 million orders per second using commodity hardware.4 Processing lots of transactions with low-latency and none of the complexities of concurrent code - how can I resist digging into that Fortunately another difference LMAX has to other financial companies is that they are quite happy to talk about their technological decisions. So now LMAX has been in production for a while its time to explore their fascinating design. Overall Structure Figure 1: LMAXs architecture in three blobs At a top level, the architecture has three parts business logic processor5 input disruptor output disruptors As its name implies, the business logic processor handles all the business logic in the application. As I indicated above, it does this as a single-threaded java program which reacts to method calls and produces output events. Consequently its a simple java program that doesnt require any platform frameworks to run other than the JVM itself, which allows it to be easily run in test environments. Although the Business Logic Processor can run in a simple environment for testing, there is rather more involved choreography to get it to run in a production setting. Input messages need to be taken off a network gateway and unmarshaled, replicated and journaled. Output messages need to be marshaled for the network. These tasks are handled by the input and output disruptors. Unlike the Business Logic Processor, these are concurrent components, since they involve IO operations which are both slow and independent. They were designed and built especially for LMAX, but they (like the overall architecture) are applicable elsewhere. Business Logic Processor Keeping it all in memory The Business Logic Processor takes input messages sequentially (in the form of a method invocation), runs business logic on it, and emits output events. It operates entirely in-memory, there is no database or other persistent store. Keeping all data in-memory has two important benefits. Firstly its fast - theres no database to provide slow IO to access, nor is there any transactional behavior to execute since all the processing is done sequentially. The second advantage is that it simplifies programming - theres no objectrelational mapping to do. All the code can be written using Javas object model without having to make any compromises for the mapping to a database. Using an in-memory structure has an important consequence - what happens if everything crashes Even the most resilient systems are vulnerable to someone pulling the power. The heart of dealing with this is Event Sourcing - which means that the current state of the Business Logic Processor is entirely derivable by processing the input events. As long as the input event stream is kept in a durable store (which is one of the jobs of the input disruptor) you can always recreate the current state of the business logic engine by replaying the events. A good way to understand this is to think of a version control system. Version control systems are a sequence of commits, at any time you can build a working copy by applying those commits. VCSs are more complicated than the Business Logic Processor because they must support branching, while the Business Logic Processor is a simple sequence. So, in theory, you can always rebuild the state of the Business Logic Processor by reprocessing all the events. In practice, however, that would take too long should you need to spin one up. So, just as with version control systems, LMAX can make snapshots of the Business Logic Processor state and restore from the snapshots. They take a snapshot every night during periods of low activity. Restarting the Business Logic Processor is fast, a full restart - including restarting the JVM, loading a recent snapshot, and replaying a days worth of journals - takes less than a minute. Snapshots make starting up a new Business Logic Processor faster, but not quickly enough should a Business Logic Processor crash at 2pm. As a result LMAX keeps multiple Business Logic Processors running all the time6. Each input event is processed by multiple processors, but all but one processor has its output ignored. Should the live processor fail, the system switches to another one. This ability to handle fail-over is another benefit of using Event Sourcing. By event sourcing into replicas they can switch between processors in a matter of micro-seconds. As well as taking snapshots every night, they also restart the Business Logic Processors every night. The replication allows them to do this with no downtime, so they continue to process trades 247. For more background on Event Sourcing, see the draft pattern on my site from a few years ago. The article is more focused on handling temporal relationships rather than the benefits that LMAX use, but it does explain the core idea. Event Sourcing is valuable because it allows the processor to run entirely in-memory, but it has another considerable advantage for diagnostics. If some unexpected behavior occurs, the team copies the sequence of events to their development environment and replays them there. This allows them to examine what happened much more easily than is possible in most environments. This diagnostic capability extends to business diagnostics. There are some business tasks, such as in risk management, that require significant computation that isnt needed for processing orders. An example is getting a list of the top 20 customers by risk profile based on their current trading positions. The team handles this by spinning up a replicate domain model and carrying out the computation there, where it wont interfere with the core order processing. These analysis domain models can have variant data models, keep different data sets in memory, and run on different machines. Tuning performance So far Ive explained that the key to the speed of the Business Logic Processor is doing everything sequentially, in-memory. Just doing this (and nothing really stupid) allows developers to write code that can process 10K TPS7. They then found that concentrating on the simple elements of good code could bring this up into the 100K TPS range. This just needs well-factored code and small methods - essentially this allows Hotspot to do a better job of optimizing and for CPUs to be more efficient in caching the code as its running. It took a bit more cleverness to go up another order of magnitude. There are several things that the LMAX team found helpful to get there. One was to write custom implementations of the java collections that were designed to be cache-friendly and careful with garbage8. An example of this is using primitive java longs as hashmap keys with a specially written array backed Map implementation ( LongToObjectHashMap ). In general theyve found that choice of data structures often makes a big difference, Most programmers just grab whatever List they used last time rather than thinking which implementation is the right one for this context.9 Another technique to reach that top level of performance is putting attention into performance testing. Ive long noticed that people talk a lot about techniques to improve performance, but the one thing that really makes a difference is to test it. Even good programmers are very good at constructing performance arguments that end up being wrong, so the best programmers prefer profilers and test cases to speculation.10 The LMAX team has also found that writing tests first is a very effective discipline for performance tests. Programming Model This style of processing does introduce some constraints into the way you write and organize the business logic. The first of these is that you have to tease out any interaction with external services. An external service call is going to be slow, and with a single thread will halt the entire order processing machine. As a result you cant make calls to external services within the business logic. Instead you need to finish that interaction with an output event, and wait for another input event to pick it back up again. Ill use a simple non-LMAX example to illustrate. Imagine you are making an order for jelly beans by credit card. A simple retailing system would take your order information, use a credit card validation service to check your credit card number, and then confirm your order - all within a single operation. The thread processing your order would block while waiting for the credit card to be checked, but that block wouldnt be very long for the user, and the server can always run another thread on the processor while its waiting. In the LMAX architecture, you would split this operation into two. The first operation would capture the order information and finish by outputting an event (credit card validation requested) to the credit card company. The Business Logic Processor would then carry on processing events for other customers until it received a credit-card-validated event in its input event stream. On processing that event it would carry out the confirmation tasks for that order. Working in this kind of event-driven, asynchronous style, is somewhat unusual - although using asynchrony to improve the responsiveness of an application is a familiar technique. It also helps the business process be more resilient, as you have to be more explicit in thinking about the different things that can happen with the remote application. A second feature of the programming model lies in error handling. The traditional model of sessions and database transactions provides a helpful error handling capability. Should anything go wrong, its easy to throw away everything that happened so far in the interaction. Session data is transient, and can be discarded, at the cost of some irritation to the user if in the middle of something complicated. If an error occurs on the database side you can rollback the transaction. LMAXs in-memory structures are persistent across input events, so if there is an error its important to not leave that memory in an inconsistent state. However theres no automated rollback facility. As a consequence the LMAX team puts a lot of attention into ensuring the input events are fully valid before doing any mutation of the in-memory persistent state. They have found that testing is a key tool in flushing out these kinds of problems before going into production. Input and Output Disruptors Although the business logic occurs in a single thread, there are a number tasks to be done before we can invoke a business object method. The original input for processing comes off the wire in the form of a message, this message needs to be unmarshaled into a form convenient for Business Logic Processor to use. Event Sourcing relies on keeping a durable journal of all the input events, so each input message needs to be journaled onto a durable store. Finally the architecture relies on a cluster of Business Logic Processors, so we have to replicate the input messages across this cluster. Similarly on the output side, the output events need to be marshaled for transmission over the network. Figure 2: The activities done by the input disruptor (using UML activity diagram notation) The replicator and journaler involve IO and therefore are relatively slow. After all the central idea of Business Logic Processor is that it avoids doing any IO. Also these three tasks are relatively independent, all of them need to be done before the Business Logic Processor works on a message, but they can done in any order. So unlike with the Business Logic Processor, where each trade changes the market for subsequent trades, there is a natural fit for concurrency. To handle this concurrency the LMAX team developed a special concurrency component, which they call a Disruptor 11 . A equipe LMAX lançou o código-fonte para o Disruptor com uma licença de código aberto. At a crude level you can think of a Disruptor as a multicast graph of queues where producers put objects on it that are sent to all the consumers for parallel consumption through separate downstream queues. When you look inside you see that this network of queues is really a single data structure - a ring buffer. Each producer and consumer has a sequence counter to indicate which slot in the buffer its currently working on. Each producerconsumer writes its own sequence counter but can read the others sequence counters. This way the producer can read the consumers counters to ensure the slot it wants to write in is available without any locks on the counters. Similarly a consumer can ensure it only processes messages once another consumer is done with it by watching the counters. Figure 3: The input disruptor coordinates one producer and four consumers Output disruptors are similar but they only have two sequential consumers for marshaling and output.12 Output events are organized into several topics, so that messages can be sent to only the receivers who are interested in them. Each topic has its own disruptor. The disruptors Ive described are used in a style with one producer and multiple consumers, but this isnt a limitation of the design of the disruptor. The disruptor can work with multiple producers too, in this case it still doesnt need locks.13 A benefit of the disruptor design is that it makes it easier for consumers to catch up quickly if they run into a problem and fall behind. If the unmarshaler has a problem when processing on slot 15 and returns when the receiver is on slot 31, it can read data from slots 16-30 in one batch to catch up. This batch read of the data from the disruptor makes it easier for lagging consumers to catch up quickly, thus reducing overall latency. Ive described things here, with one each of the journaler, replicator, and unmarshaler - this indeed is what LMAX does. But the design would allow multiple of these components to run. If you ran two journalers then one would take the even slots and the other journaler would take the odd slots. This allows further concurrency of these IO operations should this become necessary. The ring buffers are large: 20 million slots for input buffer and 4 million slots for each of the output buffers. The sequence counters are 64bit long integers that increase monotonically even as the ring slots wrap.14 The buffer is set to a size thats a power of two so the compiler can do an efficient modulus operation to map from the sequence counter number to the slot number. Like the rest of the system, the disruptors are bounced overnight. This bounce is mainly done to wipe memory so that there is less chance of an expensive garbage collection event during trading. (I also think its a good habit to regularly restart, so that you rehearse how to do it for emergencies.) The journalers job is to store all the events in a durable form, so that they can be replayed should anything go wrong. LMAX does not use a database for this, just the file system. They stream the events onto the disk. In modern terms, mechanical disks are horribly slow for random access, but very fast for streaming - hence the tag-line disk is the new tape.15 Earlier on I mentioned that LMAX runs multiple copies of its system in a cluster to support rapid failover. The replicator keeps these nodes in sync. All communication in LMAX uses IP multicasting, so clients dont need to know which IP address is the master node. Only the master node listens directly to input events and runs a replicator. The replicator broadcasts the input events to the slave nodes. Should the master node go down, its lack of heartbeat will be noticed, another node becomes master, starts processing input events, and starts its replicator. Each node has its own input disruptor and thus has its own journal and does its own unmarshaling. Even with IP multicasting, replication is still needed because IP messages can arrive in a different order on different nodes. The master node provides a deterministic sequence for the rest of the processing. The unmarshaler turns the event data from the wire into a java object that can be used to invoke behavior on the Business Logic Processor. Therefore, unlike the other consumers, it needs to modify the data in the ring buffer so it can store this unmarshaled object. The rule here is that consumers are permitted to write to the ring buffer, but each writable field can only have one parallel consumer thats allowed to write to it. This preserves the principle of only having a single writer. 16 Figure 4: The LMAX architecture with the disruptors expanded The disruptor is a general purpose component that can be used outside of the LMAX system. Usually financial companies are very secretive about their systems, keeping quiet even about items that arent germane to their business. Not just has LMAX been open about its overall architecture, they have open-sourced the disruptor code - an act that makes me very happy. Not just will this allow other organizations to make use of the disruptor, it will also allow for more testing of its concurrency properties. Queues and their lack of mechanical sympathy The LMAX architecture caught peoples attention because its a very different way of approaching a high performance system to what most people are thinking about. So far Ive talked about how it works, but havent delved too much into why it was developed this way. This tale is interesting in itself, because this architecture didnt just appear. It took a long time of trying more conventional alternatives, and realizing where they were flawed, before the team settled on this one. Most business systems these days have a core architecture that relies on multiple active sessions coordinated through a transactional database. The LMAX team were familiar with this approach, and confident that it wouldnt work for LMAX. This assessment was founded in the experiences of Betfair - the parent company who set up LMAX. Betfair is a betting site that allows people to bet on sporting events. It handles very high volumes of traffic with a lot of contention - sports bets tend to burst around particular events. To make this work they have one of the hottest database installations around and have had to do many unnatural acts in order to make it work. Based on this experience they knew how difficult it was to maintain Betfairs performance and were sure that this kind of architecture would not work for the very low latency that a trading site would require. As a result they had to find a different approach. Their initial approach was to follow what so many are saying these days - that to get high performance you need to use explicit concurrency. For this scenario, this means allowing orders to be processed by multiple threads in parallel. However, as is often the case with concurrency, the difficulty comes because these threads have to communicate with each other. Processing an order changes market conditions and these conditions need to be communicated. The approach they explored early on was the Actor model and its cousin SEDA. The Actor model relies on independent, active objects with their own thread that communicate with each other via queues. Many people find this kind of concurrency model much easier to deal with than trying to do something based on locking primitives. The team built a prototype exchange using the actor model and did performance tests on it. What they found was that the processors spent more time managing queues than doing the real logic of the application. Queue access was a bottleneck. When pushing performance like this, it starts to become important to take account of the way modern hardware is constructed. The phrase Martin Thompson likes to use is mechanical sympathy. The term comes from race car driving and it reflects the driver having an innate feel for the car, so they are able to feel how to get the best out of it. Many programmers, and I confess I fall into this camp, dont have much mechanical sympathy for how programming interacts with hardware. Whats worse is that many programmers think they have mechanical sympathy, but its built on notions of how hardware used to work that are now many years out of date. One of the dominant factors with modern CPUs that affects latency, is how the CPU interacts with memory. These days going to main memory is a very slow operation in CPU-terms. CPUs have multiple levels of cache, each of which of is significantly faster. So to increase speed you want to get your code and data in those caches. At one level, the actor model helps here. You can think of an actor as its own object that clusters code and data, which is a natural unit for caching. But actors need to communicate, which they do through queues - and the LMAX team observed that its the queues that interfere with caching. The explanation runs like this: in order to put some data on a queue, you need to write to that queue. Similarly, to take data off the queue, you need to write to the queue to perform the removal. This is write contention - more than one client may need to write to the same data structure. To deal with the write contention a queue often uses locks. But if a lock is used, that can cause a context switch to the kernel. When this happens the processor involved is likely to lose the data in its caches. The conclusion they came to was that to get the best caching behavior, you need a design that has only one core writing to any memory location17. Multiple readers are fine, processors often use special high-speed links between their caches. But queues fail the one-writer principle. This analysis led the LMAX team to a couple of conclusions. Firstly it led to the design of the disruptor, which determinedly follows the single-writer constraint. Secondly it led to idea of exploring the single-threaded business logic approach, asking the question of how fast a single thread can go if its freed of concurrency management. The essence of working on a single thread, is to ensure that you have one thread running on one core, the caches warm up, and as much memory access as possible goes to the caches rather than to main memory. This means that both the code and the working set of data needs to be as consistently accessed as possible. Also keeping small objects with code and data together allows them to be swapped between the caches as a unit, simplifying the cache management and again improving performance. An essential part of the path to the LMAX architecture was the use of performance testing. The consideration and abandonment of an actor-based approach came from building and performance testing a prototype. Similarly much of the steps in improving the performance of the various components were enabled by performance tests. Mechanical sympathy is very valuable - it helps to form hypotheses about what improvements you can make, and guides you to forward steps rather than backward ones - but in the end its the testing gives you the convincing evidence. Performance testing in this style, however, is not a well-understood topic. Regularly the LMAX team stresses that coming up with meaningful performance tests is often harder than developing the production code. Again mechanical sympathy is important to developing the right tests. Testing a low level concurrency component is meaningless unless you take into account the caching behavior of the CPU. One particular lesson is the importance of writing tests against null components to ensure the performance test is fast enough to really measure what real components are doing. Writing fast test code is no easier than writing fast production code and its too easy to get false results because the test isnt as fast as the component its trying to measure. Should you use this architecture At first glance, this architecture appears to be for a very small niche. After all the driver that led to it was to be able to run lots of complex transactions with very low latency - most applications dont need to run at 6 million TPS. But the thing that fascinates me about this application, is that they have ended up with a design which removes much of the programming complexity that plagues many software projects. The traditional model of concurrent sessions surrounding a transactional database isnt free of hassles. Theres usually a non-trivial effort that goes into the relationship with the database. Objectrelational mapping tools can help much of the pain of dealing with a database, but it doesnt deal with it all. Most performance tuning of enterprise applications involves futzing around with SQL. These days, you can get more main memory into your servers than us old guys could get as disk space. More and more applications are quite capable of putting all their working set in main memory - thus eliminating a source of both complexity and sluggishness. Event Sourcing provides a way to solve the durability problem for an in-memory system, running everything in a single thread solves the concurrency issue. The LMAX experience suggests that as long as you need less than a few million TPS, youll have enough performance headroom. There is a considerable overlap here with the growing interest in CQRS. An event sourced, in-memory processor is a natural choice for the command-side of a CQRS system. (Although the LMAX team does not currently use CQRS.) So what indicates you shouldnt go down this path This is always a tricky questions for little-known techniques like this, since the profession needs more time to explore its boundaries. A starting point, however, is to think of the characteristics that encourage the architecture. One characteristic is that this is a connected domain where processing one transaction always has the potential to change how following ones are processed. With transactions that are more independent of each other, theres less need to coordinate, so using separate processors running in parallel becomes more attractive. LMAX concentrates on figuring the consequences of how events change the world. Many sites are more about taking an existing store of information and rendering various combinations of that information to as many eyeballs as they can find - eg think of any media site. Here the architectural challenge often centers on getting your caches right. Another characteristic of LMAX is that this is a backend system, so its reasonable to consider how applicable it would be for something acting in an interactive mode. Increasingly web application are helping us get used to server systems that react to requests, an aspect that does fit in well with this architecture. Where this architecture goes further than most such systems is its absolute use of asynchronous communications, resulting in the changes to the programming model that I outlined earlier. These changes will take some getting used to for most teams. Most people tend to think of programming in synchronous terms and are not used to dealing with asynchrony. Yet its long been true that asynchronous communication is an essential tool for responsiveness. It will be interesting to see if the wider use of asynchronous communication in the javascript world, with AJAX and node. js, will encourage more people to investigate this style. The LMAX team found that while it took a bit of time to adjust to asynchronous style, it soon became natural and often easier. In particular error handling was much easier to deal with under this approach. The LMAX team certainly feels that the days of the coordinating transactional database are numbered. The fact that you can write software more easily using this kind of architecture and that it runs more quickly removes much of the justification for the traditional central database. For my part, I find this a very exciting story. Much of my goal is to concentrate on software that models complex domains. An architecture like this provides good separation of concerns, allowing people to focus on Domain-Driven Design and keeping much of the platform complexity well separated. The close coupling between domain objects and databases has always been an irritation - approaches like this suggest a way out. if you found this article useful, please share it. I appreciate the feedback and encouragement

No comments:

Post a Comment