Friday 25 August 2017

Forex Idealpro


PLACAS DE DADOS DE CORREDORES INTERATIVOS AmiBroker agora suporta as cotações de transmissão em tempo real dos intermediários interativos TWS IMPORTANTE: NÃO PRECISA INSTALAR o plugin se você instalou o AmiBroker 5.70 ou posterior. É INSTALADO previamente pela configuração do AmiBroker. Suporta até 100 símbolos de transmissão em tempo real (igual ao limite IB TWS) suporta todos os intervalos de tempo base: 15, 5, 1 minuto, 15, 5 segundos, marca a conexão automática (não é necessário transferir manualmente a conexão entrante TWS) suporta até 30 (180) DADOS dados intraduais BACKFILL no intervalo de barra de 1 minuto até 2000 barras de preenchimento usando intervalos de barras de 1 segundo de 15 segundos funciona em todas as versões do Windows de 32 bits 180 dias de preenchimento pode ser lento devido à aceleração IB As solicitações de preenchimento OBSERVAÇÃO SOBRE O DESEMPENHO DO IBTWS: o preenchimento do IB TWS é muito limitado (1 símbolo por vez) e MUITO MUITO lento. O IB diminui os preenchimentos e você não pode enviar mais de 60 solicitações dentro de 5 minutos (é igual a um mês de dados de 1 minuto para apenas 12 símbolos). Para preenchimentos muito mais rápidos, recomendamos eSignal ou IQFeed. REQUISITOS IMPORTANTES DO SISTEMA NOTA: enquanto o próprio AmiBroker não possui grandes requisitos (consulte a página de Introdução), Interactive Brokers TWS é um aplicativo baseado em Java que é memória e CPU com fome. Você precisaria ter pelo menos 800MHz CPU para usar TWS. Consulte a página de requisitos do sistema TWS oficial: interactivebrokersensoftwarerequirements. php NOTA IMPORTANTE SOBRE O BACKFILL IB EM TICK MODE: A melhor resolução de BACKFILLS que o Interactive Brokers TWS oferece é 1-SECOND bars (veja os documentos da TWS API aqui). Isso significa que, embora você possa coletar dados em tempo real de transmissão em formato de tiquetaque, o recheio sempre terá resolução limitada a barras de 1 segundo. Além disso, os dados de transmissão do IB TWS NÃO são tick-by-tick, mas sim 0.2-0.3 segundos instantâneos, leia isso para detalhes: interactivebrokerscgi-bindiscusboard-auth. plfile237364.html Por esse motivo, recomendamos o uso de intervalos mais altos, como 5 segundos, 15- Seg ou melhor ainda 1 minuto. Para Windows XP, Vista, Windows 7, Windows NT, 98 inclui uma correção de compatibilidade para TWS 907 Para Windows XP, Vista, Windows 7, Windows NT, 98 Atualizado para AmiBroker 5.30 (já está incluído na configuração do AmiBroker 5.30) 2.0 .2. Lançado em 2 de outubro de 2009 para o Windows XP, o Vista, o Win 7, o Win 2000, o Win NT, o Win98 suporta o tempo de duração de 64 bits e o volume de volume do flutuador (AmiBroker 4.27 e acima) no Vista e no Windows 7 versões anteriores do plugin IB bloqueadas ao solicitar um símbolo inválido porque A função AfxIsValidAddress está quebrada no VistaWin7. Corrigido por regravar o código para não usar AfxIsValidAddress mais. Correção para índices não-americanos negociados com moedas diferentes do USD 1.8.2 lançado em 23 de outubro de 2008, o plugin agora aceita códigos de tipo de segurança de uma única letra, além de códigos de 3 letras. Portanto, agora o tipo de segurança pode ser: S ou STK para ações F ou FUT para futuros O ou OPT para opções P ou FOP para opções de futuros C ou caixa para moedas (Forex) I ou IND para índices Isso é fornecido para encurtar símbolos para instrumentos cotados Em moedas não norte-americanas, então elas se encaixam no máximo de 25 caracteres. Por exemplo, quotFSMI DEC 08-SOFFEX-F-CHFquot 1.8.1 lançado em 22 de outubro de 2008 devido à possível ambiguidade do roteamento SMART quando o mesmo símbolo é negociado com várias moedas, o plugin IB agora permite especificar MOEDA Em um símbolo. O formato do símbolo é agora: SYMBOL-EXCHANGE-TYPE-CURRENCY. Todos os símbolos que não possuem especificação de moeda explícita usam USD agora (exceto o forex). A moeda padrão é USD e é usada quando nada é especificado como 4ª parte do símbolo. Então, por exemplo, a MSFT obtém internamente resolvido para MSFT-SMART-STK-USD1.8.0 lançado em 15 de outubro de 2008 (obsoleto - use 1.8.1) para corrigir o erro de IDtot do ticker quotduplicado com o TWS mais novo quando mais de 5 dias de preenchimento foi solicitado 1.7 .1 lançado em 10 de junho de 2008 Recuperado prolongado até 180 dias (o experimento pode ser lento sujeito a aceleração IB) (reenchimento de um ano removido devido à instabilidade) 1.7.0 lançado 8 de maio de 2008 Preço aberto disponível na janela de cotação RT (para ações ) Enchimento prolongado 180 dias (o experimento pode ser lento sujeito a aceleração do IB) Melhor manipulação de reconexão automática na desconexão de rede Manipulação de código de erro atualizada (código 162 - violação de estimulação de dados) Atualizado para usar a nova API TWS 9.41 diminuição da carga da CPU durante o recheio diminuiu a carga da CPU durante Períodos de alta atividade atualizados para o mais novo TWSAPI 9.0 e testados com o mais novo TWS 863, bem como 862 e 861. 1.6.6 lançado 6 de julho de 2006 PrimaryExchange agora está configurado para seqüência de caracteres vazia e somente o símbolo local é você Quando solicitou dados. Isso resolve o problema de simbolo inválido ocorrido em algumas contas durante as últimas 2 semanas após alterações aparentes no IB. 1.6.7 lançado em 31 de março de 2006, agora a conexão de streaming usa buffer pequeno, enquanto a conexão de preenchimento usa proteção de buffer grande adicionada para impedir o preenchimento quando o usuário percorre a lista de símbolos e o ticker inválido é encontrado 1.6.0 lançado em 30 de março de 2006, adicionou o tratamento do erro TWS Mensagem 300 (não encontrou o Eid) adicionado manipulação da mensagem de erro TWS 165 (Desconexão HDMS) - permite a solução alternativa TWS aceleração adicionada quotCancel Backfillquot menu opção adicionada quotMinimumquot comprimento de preenchimento que preenchimentos em menos de um dia, se você já possui alguns dados de hoje mais recentemente O comprimento de preenchimento selecionado é armazenado entre a sessão adicionada conexão separada para preenchimento para problemas de solução alternativa TWS com enrolamentos suspensos mais reconexão automática se o preenchimento exceder ou desconectado HDMS adicionado algumas verificações de tempo de execução para ponteiros válidos para solução alternativa erro TWS de enviar IDs incorretas para certas citações de mensagens após o preenchimento São liberados da notificação de getquotes adicionada pela memória do plugin Para uso em versões futuras do problema fixo AmiBroker com símbolos - IND (bug apareceu em 1.5.0) 1.4.4 código de soquete reutilizado (o mais novo estava funcionando bem em todas as máquinas, exceto uma) 1.5.0 lançado 27 de janeiro de 2006 1 O comprimento minimo do preenchimento é prolongado até 30 dias. Usuário selecionável a partir do menu do botão RIGHT do mouse sobre a área de status do plugin. (Observe que devido a limitações de limitação TWS com mais de 5 dias são divididos em pedaços de 5 dias e baixados sequencialmente) Solução implementada para o jeito IB de enviar eventos tickSize O problema era que IB às vezes repete muitas vezes o mesmo tiquetaque e às vezes salta alguns carrapatos e Acumule-os em um evento tickSize LASTSIZE. Isso ocorre porque o feed do IB não foi projetado como tick-by-tick e nunca pretendia criar séries de timeampsales, mas sim apenas para atualizar a grade de exibição TWS. Agora, o plugin tenta resolver esta estranheza ao ignorar os eventos duplicados tickSize LASTSIZE (com o mesmo tamanho) e corrigir os carrapatos ausentes, o volume CUMULATIVO enviado com o evento tickSize VOLUME. A correção é necessária porque, sem isso, acabaríamos por ter um volume total incorreto (às vezes, os negócios reais podem ter os mesmos eventos, de modo que múltiplos carrapatos reais podem ter o mesmo preço, infelizmente não há como detectar sempre que seja real ou duplicado gerado pelo IB, então A correção de acordo com o volume acumulado é o único caminho a seguir). O plugin agora aceita quotOquot e quotOPquot como especificação de tipo e trata-o como quotOPTquot Isso permite obter cotações para algumas opções que têm símbolos muito longos (excedendo 26 caracteres permitidos pelo AB). Por exemplo, para obter as opções DAX, use esses símbolos: C ODAX MAR 06 5500-DTB-O P ODAX MAR 06 5500-DTB-O (note que existem dois espaços entre 06 (código de ano) e 5500 (preço).) Corrigido alguns Problemas com o Microsofts Implementação do buggy CSocket A mensagem de erro da API IB 165 é usada agora para detectar quando o preenchimento está disponível ou não (a conta de demonstração, por exemplo, não oferece backfill). As partes principais da API são reescritas para usar sockets de buffer rápidos - oferece uma melhoria de desempenho até 10x (versões anteriores Utilizou o código EClientSocket fornecido como parte da API TWS. Desafortunadamente, este código estava usando leitura de um byte-a-hora a partir do soquete e era um desempenho terrível quando os preenchimentos eram mais longos do que um dia. O novo código de soquete em buffer pode ler Até 4096 bytes ao mesmo tempo) preenchimento completo de 5 dias para todos os símbolos (intervalo de barra de 1 minuto) O IDEALPRO agora usa MIDPRICE em vez de BID para obter um preenchimento mais limpo, mas o usuário pode retornar ao BID na tela de configuração. Esta versão oferece um desempenho ligeiramente melhorado (menos uso da CPU) 1.4.1 lançado 13 de junho de 2005 Esta versão corrige a atualização em tempo real para o mercado IDEALPRO (forex), ou seja, símbolos como EUR. USD-IDEALPRO-CASH são atualizados corretamente em tempo real. (O IB não envia a última atualização de preços de negociação para Forex, portanto, o preço de BID é usado em vez disso) suporta backfill (leia abaixo os detalhes). Não requer nenhuma instalação de API. Já está incluído na configuração completa do AmiBroker 4.70.5 a) o backfill não está disponível nas contas DEMO (esta é a limitação do TWS) b) os dados de preenchimento para alguns símbolos podem não estar presentes nos servidores do IB c) UseRTH (reposição de horas prolongadas onoff switch ) Não parece estar funcionando (erro no TWS reportado ao IB já) d) o TWS suporta apenas um preenchimento de cada vez, de modo que o plugin evita que ele acione mais. E) O TWS só permite que determinadas quantidades de dados sejam baixadas dependendo do intervalo de tempo de base. NOTA: Brokers interativos TWS é uma aplicação com fome de CPU, portanto, para melhores resultados, recomendamos usar a máquina com processador de 1GHz ou mais rápido. Para usar o plugin de dados Interactive Brokers com o AmiBroker, você precisa: NÃO PRECISA INSTALAR o plugin se você instalou o AmiBroker 5.70 ou posterior. É JÁ incluído. Faça o download do plugin IB de: amibrokerbinib204IB. dll Versão atual STABLE do IB. DLL: 2.0.4 e copie-o para a subpasta PLUGINS do diretório AmiBroker. Execute TWS na Internet ou faça o download do TWS autônomo em TWS, selecione Configure - gt API - gt Habilite clientes Active X e Socket. Digite também 127.0.0.1 no menu de endereços IP TWS, Configurar-gtAPI-gtTrusted para evitar quotAllow entrante connectionquot dialog. Execute o AmiBroker e crie um novo banco de dados com o plugin Interactive Brokers como fonte de dados, seguindo estas etapas: Escolha o banco de dados File-gtNew Digite um novo nome de pasta (por exemplo: C: Program FilesAmiBrokerIB) e clique em Criar como mostrado na figura abaixo: Escolha InteractiveBrokers (R) Dados Plug-in do Combo da fonte de dados e Ativar do armazenamento de dados locais Digite 30000 ou mais em quot Número de barras para carregar o campo quot Agora escolha o intervalo de tempo Base. Os intervalos suportados são: EOD, por hora, 15 minutos, 5 minutos, 1 minuto. A edição profissional do AmiBroker também permite selecionar intervalos de Tick, 5 segundos e 15 segundos. Observe que o preenchimento está em intervalo de barras de 1 minuto ou menos (limitação TWS). Se você quiser ter longas histórias diárias e gráficos intradiários, você deve considerar executar duas instâncias do AmiBroker. Um para gráficos EOD e segundo para gráficos intraday. Ambas as instâncias podem usar IB como fonte de dados. A partir de agora, o seu AmiBroker lê cotações diretamente dos Interactive Brokers. O formato de símbolo agora usa o modo de símbolo do TWS, não o modo subjacente. O modo de símbolo no TWS pode ser visto na opção de menu do modo View-gtSymbol no TWS. O formato é: SYMBOL - EXCHANGE - TYPE-CURRENCY SYMBOL é o mesmo que a coluna de símbolos, conforme exibido no TWS, enquanto no modo de símbolo O INTERCÂMBIO (opcional) é a troca d no TWS enquanto estiver no modo de símbolo TYPE (opcional) é um dos seguintes: STK ou S - ações, FUT ou F - futuros, FOP ou P - opções em futuros, OPT ou O - opções, IND ou I - índices, caixa ou C-cash (FX ideal) Observe que para ações apenas o INTERCÂMBIO e TIPO Os campos são opcionais. A troca será definida como BEST (SMART) e o TYPE será configurado para STK. Observe que os códigos de tipo SINGLE LETTER são permitidos SOMENTE na versão 1.8.2 e acima. MOEDA (opcional - apenas plugin versão 1.8.1 e acima) - é a moeda com a qual o símbolo é negociado. O padrão para tipos STK, FUT, FOP, OPT, IND é USD (dólar norte-americano). A moeda padrão para DINHEIRO (forex) está vazia. Tenha especial cuidado ao digitar símbolos como alguns deles (futuros) têm espaços múltiplos no nome do símbolo. Você deve digitar EXATAMENTE O MESMO número de espaços conforme fornecido nos exemplos abaixo (veja os guinchos abaixo do nome do símbolo que tornam mais fácil ver o número de caracteres) NOTAS SOBRE AS LIMITAÇÕES DA API IB: 1. O preenchimento está disponível apenas para contas REAL IB (Não na demo) 2. O preço aberto não é fornecido pelo IB. Por esse motivo, o campo Abrir está vazio na janela de cotações em tempo real. 3. Os dados do IB não incluem um carimbo de data / hora nos negócios. O tempo atual do sistema é usado para carimbo de data / hora de cada marca. COMO UTILIZAR O BACKFILL FEATURE O recurso de preenchimento no plugin 1.3.7 permite baixar 24 dados históricos intradanos para preencher as lacunas que podem ter ocorrido quando o AmiBroker TWS não está sendo executado. O recurso de preenchimento do IB é configurável a partir das Configurações do File-gtDatabase. Configure: Duas configurações principais relacionadas ao preenchimento são: 1. comprimento do pedido 2. reenchimento automático Quando o comprimento da solicitação é considerado, conforme explicado nas Notas de Versão da API TWS em: interactivebrokersensoftwareapiReleaseNotesapiBetanotes. php Atualmente, o recurso de preenchimento do IB está limitado a alguns intervalos de intervalos de barras de duração fixa. Por exemplo, você pode obter o máximo de 2000 carrapatos de 1 segundo, máximo de 10000 segundos no intervalo de 5 segundos (2000 bar), máximo de 30000 segundos no intervalo de 15 segundos (também 2000 bar) e no máximo de 5 DIAS de barras de 1 minuto. Por padrão, o AmiBroker usa quantidades máximas permitidas. Quanto ao preenchimento contingentático no primeiro acesso de dados - quando é verificado, o AmiBroker tenta voltar a preencher o símbolo quando exibir um gráfico para um símbolo dado (ou executar backtest ou digitalizar). Observe que a API TWS atualmente permite apenas um preenchimento de uma vez por isso, quando há um preenchimento já executado em segundo plano, a solicitação de preenchimento automático para o próximo símbolo será ignorada, até que o preenchimento anterior seja concluído. É conveniente ter essa opção ativada, no entanto, pode causar carga adicional na sua conexão com a Internet devido aos dados necessários para serem baixados durante o processo de preenchimento. Se você alternar o preenchimento contingente automático na primeira opção de acesso a dados, você ainda poderá preencher dados para o símbolo atual ou todos os símbolos na lista de citações em tempo real, use as opções de menu apropriadas no menu de status do plugin. A opção atual de preenchimento permite forçar o preenchimento do símbolo atualmente selecionado, enquanto os símbolos RTF do Backfill permitem forçar o preenchimento de todos os símbolos listados na janela de Cálculo Real-Time. O preenchimento de múltiplos símbolos é realizado sequencialmente (um de cada vez) devido a limitações do TWS. Durante o preenchimento de uma ferramenta, aparece informando o usuário sobre o símbolo que está sendo preenchido no momento e a cor do status do plugin muda para azul claro (turquesa) como mostrado abaixo: AmiBroker Interface de negociação automática para Interactive Brokers 1.3.8 Beta Leia-me 29 de maio de 2014 21:03 ESTA É UMA VERSÃO BETA DO SOFTWARE (veja a seção de perguntas freqüentes para uma resposta, por que é marcado como BETA quot) A NEGOCIAÇÃO AUTOMÁTICA TRABALHA CERTO RISCOS. POR FAVOR, TESTE ATENTAMENTE SEU CÓDIGO USANDO PRIMEIROS DEMO TWS E, ENTÃO, A CONTA DE TRABALHO DE PAPEL A INTEIRA DE NEGOCIAÇÃO AUTOMÁTICA É DESTINADA A FAZER O NEGOCIAÇÃO MAIS FÁCIL E MAIS RÁPIDO, MAS NÃO É DESTINADO A FUNCIONAR SEM SUPERVISÃO. NÃO DEIXE A NEGOCIAÇÃO AUTOMÁTICA DESATADA DE QUE CERTAS CIRCUNSTÂNCIAS PODEM OCORRER COMO FALHA DE INTERNET, FALHA DE ALIMENTAÇÃO, OUTRA SITUAÇÃO INESPERADA QUE PODE CONDUZIR A PERDA FINANCEIRA SÉRIA. Basta executar o instalador e seguir as instruções. Veja CHANGE LOG abaixo para obter uma lista detalhada de mudanças. AmiBroker 4.70 ou superior. Recomendado AmiBroker 5.30 especialmente no Vista e no Windows 7. Estação de trabalho TWS (DEMO, PaperTrading está OK) de roteadores interativos. Versão preferida: 907 ou superior. NÃO use TWS versão 945.1 - é buggy, especialmente a versão web. O IB Controller (BrokerIB. EXE) é um aplicativo separado que atua como um buffer entre o AmiBroker e o Interactive Brokers TWS. Aceita comandos da AmiBroker e envia ordens para recuperar informações da TWS. Também permite cancelar as ordens de transferência manualmente. O aplicativo do controlador IB é executado automaticamente pelo AmiBroker se a fórmula contiver a seguinte chamada: Após essa chamada, o aplicativo BrokerIB. EXE (IB Controller) é iniciado e a variável ibc contém o ponteiro para objeto de automação OLE que possui vários métodos (funções) que Permitir placemodifyCancelar pedidos via TWS e consultar informações de portfólio. Esses métodos (funções) são chamados como qualquer método de objeto de automação, por exemplo: se (ibc. IsConnected ()) verifique se a conexão com o IB foi bem-sucedida. Ibc. PlaceOrder (quotMSFTquot, quotBUYquot, 100, quotMKTquot, 0, 0, quayDAYquot, False ) Coloque o pedido, mas não transmita ainda Note que esta é uma interface de baixo nível para usuários avançados disponibilizados na chamada fase-um de implementação de negociação automatizada via IB. Haverá uma interface de nível superior que será implementada mais tarde. Métodos do Controlador IB (Funções): Esta função coloca uma nova ordem. A função retorna o OrderId (string) que pode ser usado mais tarde para modificar o status da ordem da ordem Parâmetros: Ticker - string que especifica o símbolo do contrato de segurança a ser comprado. O símbolo deve seguir a simbologia definida em detalhes em: amibrokerib. html Ação - especifica ação a ser tomada, os valores possíveis são: quotBUYquot, quotSELLquot, quotSSHORTquot Quantidade - o número de contratos de compartilhamento para buysell Tipo - especifica o tipo de ordem, os valores possíveis são: quotMKTquot QuotMKTCLSquot, quotLMTquot, quotLMTCLSquot, quotPROQQue, quotSTPquot, quotSTAPMTquot, quotTRAILquot, quotRELquot, quotVWAPquot - consulte a documentação do Interactive Brokers TWS para obter mais informações sobre os tipos de ordem LimitPrice - isso define o preço limite para limite e stop limite Order StopPrice - isso define stop Preço para ordens de parada TimeInForce - define o tempo em vigor da ordem, os valores possíveis são: quotDAYquot, quotGTCquot, quotIOCquot, quotGTDquot Começando a partir de v1.0.8 O campo TimeInForce em PlaceOrderModifyOrder aceita especificações GTD e GAT GTD - Good Till Date - indica que a ordem Deve permanecer trabalhado até a hora e a data definidas. Especificação da data boa até a data GTD YYYYMMDD HH: MM: SS TZONE em que: AAAA é o ano de 4 dígitos. MM é um mês de 2 dígitos. DD é um dia de 2 dígitos. HH é uma hora de 2 dígitos. MM é 2 dígitos. SS é 2 dígitos em segundo (OPCIONAL) TZONE é hora Zona (OPCIONAL) Depois das especificações regulares do TimeInForce (DAY, GTC, GTD), você pode adicionar uma parte adicional GoodAfterTime (GAT). A parte GAT vem depois do ponto-e-vírgula. Isso indica que o comércio deve ser enviado após a hora e a data definidas: DAYGAT AAAAMMDD HH: MM: SS TZONE - ordem do dia válida após o horário especificado GTCGAT AAAAMMDD HH: MM: SS TZONE - bom até a ordem cancelada válida após o tempo especificado GTD yyyymmdd hh: Mm: ss tzoneGAT AAAAMMDD HH: MM: SS TZONE - Ordem GTD válida após o tempo especificado em que: AAAA é de 4 dígitos. O MM é um mês de 2 dígitos O DD é um dia de 2 dígitos. HH é uma hora de 2 dígitos. MM é 2 dígitos. SS é de 2 dígitos. (OPCIONAL) TZONE é fuso horário (OPCIONAL) Nota: não deve haver ESPAÇO caracterizados entre o ponto-e-vírgula e a cadeia GAT. Ibc. PlaceOrder (MSFT. COMPRAR. 100. LMT. 27. 0. DAYGAT 20051214 18:00:00 GMT. Verdadeiro) - ordem limite do dia bom depois de 14 de dezembro de 2005, 18:00 GMT ibc. PlaceOrder (MSFT. COMPRAR. 100. LMT 27. 0. GTD 20051215 17:00:00 GMTGAT 20051214 18:00:00 GMT. Verdadeiro) - ordem limite válida de 14 de dezembro de 2005 18:00 a 15 de dezembro de 2005 17:00 GMT ibc. PlaceOrder (MSFT. COMPRAR. 100. LMT. 27. 0. GTD 20051215 19:00:00 GMT. Verdadeiro) - ordem limite válida até agora até 15 de dezembro de 2005 19:00 GMT Transmissão - bandeira booleana que especifica se a ordem dada deve ser Na verdade transmitido para a troca. Se esta bandeira estiver definida como FALSA, a ordem NÃO é transmitida, mas aparece na estação de trabalho TWS para que você possa pressionar transmiti-la manualmente mais tarde, parâmetros adicionais para IBController 1.0.4 ou superior: TickSize - define a flutuação mínima de preço permitida para o símbolo dado expresso em pips (0.0001 ). Para a maioria das ações dos EUA é 100 (representa 0.01 movimentos), para a maioria das moedas: 1 (representa 0.0001 movimentos), se o movimento mínimo for menor que 0.0001 você pode usar valores fracionários, por exemplo, 1100 para 0.000001 mover. Parâmetros adicionais para IBController 1.0.8 Ou superior: Atributos - é uma seqüência de caracteres que permite especificar atributos de ordem adicionais (lista separada por vírgula).outsideRTH - se especificado significa que a ordem será acionada não só durante as Horas regulares de negociação (RTH), mas também na negociação estendida (pré-mercado) Aplica-se para parar pedidos, ordens condicionais e alertas, é usado pela lógica desencadeante. Se não for especificado (falso), as ordens serão ativadas SOMENTE durante o RTH. AllOrNone - preencha tudo ou nada em tudo eTradeOnly - troque com orçamentos eletrônicos somente empresaQuoteOnly - troque com citações de empresa apenas Versão 1.1 ignoreRth rthOnly flags são OBSOLETOS agora e não são suportados, pois a API TWS diminuiu o suporte para aqueles. Por padrão, todos esses sinalizadores são INACTIVOS (DESLIGADOS) Exemplo: ibc. PlaceOrder (MSFT. COMPRAR. 1000. LMT. 27. 0. GTD 20051215 19:00:00 GMT. Verdadeiro. 100. allOrNone) (Observe que o parâmetro opcional TickSize DEVE Ser especificado se você quiser usar Atributos) ParentID - é uma seqüência de caracteres que especifica o identificador da ordem principal (retornado pela chamada PlaceOrder anterior), permitindo que você coloque pedidos do BRACKET. ParentID ibc. PlaceOrder (MSFT. COMPRAR. 1000. LMT. 27. 0. GTC. Falso) ibc. PlaceOrder (MSFT. VENDER. 1000. LMT. 28. 0. GTC. Falso. 100.. ParentID) ibc. PlaceOrder ( MSFT. VENDER. 1000. STP 26. 26. GTC. Verdadeiro. 100.. ParentID) Observe que TRANSMIT flag está definido como FALSE em todas as ordens de suporte, exceto a última. Isso garante que as ordens aguardem até que o conjunto de pedidos do suporte seja concluído. Definir sinalizador Transmissão para TRUE no último transmite todo o suporte. OCAGroup - parâmetro de seqüência opcional (novo em 1.1.0) que permite definir o grupo de ordens OCA (One-Cancels-All) ordens de grupo OCA trabalham em conjunto um com o outro, então, quando uma ordem dentro do grupo é executada, as ordens restantes são canceladas . Para mais informações, veja: interactivebrokersphpwebhelpMakingTradesCreateOrderTypesoca. htmExemplo: ibc. PlaceOrder (MSFT. VENDER. 1000. LMT. 28. 0. GTC. Verdadeiro. 100.. 0. MYGROUP) ibc. PlaceOrder (MSFT. SELL. 1000. STP. 26. 26. GTC. Verdadeiro. 100.. 0. MYGROUP) OCAType - parâmetro numérico opcional (novo em 1.1.0) que permite controlar a forma como as ordens OCAGroup são tratadas quando uma ordem no grupo é parcialmente preenchida. Os valores possíveis são: 1 CANCELWITHBLOCK - outros pedidos são cancelados 2 REDUCEWITHBLOCK - outros pedidos são de tamanho reduzido e a proteção de sobrellenado é ON 3 REDUCENONBLOCK - outros pedidos são reduzidos em tamanho e a proteção de sobrellenado está OFF O valor padrão é 3 FAParams - parâmetro de string opcional (novo Em 1.1.0) - para uso com as contas de FA (Financial Advisor aka FamilyampFriends). Permite especificar o grupo de alocação da conta FA, perfil, método e porcentagem. Esses quatro parâmetros devem ser fornecidos como seqüência separada por ponto e vírgula: quotFAGroupFAProfileFAMethodFAPercentagequot. Se algum parâmetro não for necessário, ele pode ser deixado em branco, mas você precisa manter os pontos e vírgulas se houver outros parâmetros necessários. Por exemplo, para especificar a ordem que usa quotAllquot group e usa quotEqualQuantityquot, o FAParameter deve ser o seguinte: quotAllEqualQuantityquot: ibc. PlaceOrder (MSFT. COMPRAR. 1000. LMT. 27. 0. GTC. Verdadeiro. 100.. 0.. 0. AllEqualQuantity) Se você deseja usar o perfil de alocação personalizado, você pode usar: ibc. PlaceOrder (MSFT. COMPRAR. 1000. LMT. 27. 0. GTC. Verdadeiro. 100.. 0. 0. AllMyCustomProfile) Se FAParams não for fornecido e Você está usando a conta FA do que o IBc usará a atribuição padrão de quotAllAvailableEquityquot. Observe que, por padrão, o IB Controller faz logon na conta quotAllquot, que é quotaggregatequot, ou seja, detém a soma de todas as posições em todas as subcontas. Conta - parâmetro de seqüência opcional (novo em 1.3.5) - para uso com as contas FA (Financial Advisor aka FamilyampFriends). Isso permite especificar a conta de destino para a ordem das contas FampFFA IB em chamada única, em vez de depender da seqüência SetAccountPlaceOrder. Single-call PlaceOrderModifyOrder com especificação da conta permite especificar a conta sem se preocupar que outros processos de threads possam mudar a conta entre SetAccount () e PlaceOrder (). ModifyOrder (string OrderId. String Ticker. String Ação número. Quantidade. String Tipo. Número LimitPrice. Number StopPrice. String TimeInForce. Bool Transmit, número opcional TickSize 100, string opcional Atributos quotquot, string opcional ParentID quotquot. String opcional OCAGroup. Número opcional OCAType. String opcional FAParam. Cadeia opcional de contas. Esta função modifica a ordem que foi colocada antes, mas ainda não preenchida. Esta função também pode ser usada para modificar as ordens que foram enviadas com quotTransmitquot flag set to False. Além disso, quando o parâmetro OrderID está vazio, esta função funciona exatamente como o PlaceOrder (para que você possa colocar e modificar ordens usando a função ModifyOrder () sozinho). A função retorna o OrderId (string) que pode ser usado mais tarde para modificar o status da ordem da ordem Parâmetros: OrderId - Seqüência de caracteres especificando o ID de ordem a ser modificado (retornado pela chamada PlaceOrder anterior ou ModifyOrder). Se este parâmetro estiver vazio, a função coloca uma nova ordem, todos os parâmetros restantes são os mesmos que na função PlaceOrder. Na versão 1.1.0, foi adicionada uma melhoria à função ModifyOrder que, se alguns dos parâmetros opcionais como ParentID, OCAGroup, OCAType, FAParam forem Não especificado - então ele usa valores fornecidos anteriormente (durante o PlaceOrder). Isso evita, por exemplo, perder o ParentID ao chamar ModifyOrder em uma ordem filho sem currect parentID. Esta função cancela a ordem pendente. Verdadeiro - se a ordem pendente foi encontrada e a solicitação de cancelamento foi enviada, False - se não houver ordem pendente com parâmetros OrderId especificados: OrderId - string, especificando o orderID a ser modificado (retornado por PlaceOrder anterior ou ModifyOrder call). GetAccountValue (string FieldName) Esta função recupera os valores da conta. String que representa o valor. Observe que, se você precisar de número na AFL, você deve usar a função de conversão do StrToNum que converterá a string retornada por esta função para o número. Cadeia de caracteres vazia é retornada se o campo não existir ou estiver vazio. Parâmetros: FieldName - define o valor para consulta Lista de campos disponíveis (sensível a maiúsculas e minúsculas): 1. Os campos que são independentes da moeda ou expressos na moeda da conta BASE (geralmente totais): AccountCode AccountReady AccountType AccruedCash CashBalance Currency DayTradesRemaining DayTradesRemainingT1 DayTradesRemainingT2 DayTradesRemainingT3 DayTradesRemainingT4 ExchangeRate FuturesPNL Leverage-S LookAheadNextCambiar NetLiquidationByCurrency OptionMarketValue PNL RealizedPnL StockMarketValue TotalCashBalance UnrealizedPnL 2. Campos que são fornecidos separadamente para cada moeda armazenada na conta, a CUR na lista abaixo significa símbolo de moeda, portanto, para fundos e títulos denominados em USD, você verá o prefixo USD. As posições de Forex do IDEALPRO estão incluídas no CURCashBalance aqui. CURAvailableFunds-S CURAccruedCash CURAccruedCash-C CURAccruedCash-S CURAvailableFunds CURAvailableFunds-C CURBuyingPower CURCashBalance CURCurrency CUREquityWithLoanValue CUREquityWithLoanValue-C CUREquityWithLoanValue-S CURExcessLiquidity CURExcessLiquidity-C CURExcessLiquidity-S CURFullAvailableFunds CURFullAvailableFunds-C CURFullAvailableFunds-S CURFullExcessLiquidity CURFullExcessLiquidity-C CURFullExcessLiquidity-S CURFullInitMarginReq CURFullInitMarginReq-C CURFullInitMarginReq - S CURFullMaintMarginReq CURFullMaintMarginReq-C CURLookAheadAvailableFunds-S-S CURFullMaintMarginReq CURFutureOptionValue CURFuturesPNL CURGrossPositionValue CURGrossPositionValue-S CURInitMarginReq CURInitMarginReq-C CURInitMarginReq-S-S CURLeverage CURLookAheadAvailableFunds CURLookAheadAvailableFunds-C CURLookAheadExcessLiquidity CURLookAheadExcessLiquidity-C-S CURLookAheadExcessLiquidity CURLookAheadInitMarginReq CURLookAheadInitMarginReq-C-S CURLookAheadInitMarginReq CURLookAheadMaintMarginReq Curlo okAheadMaintMarginReq-C CURLookAheadMaintMarginReq-S CURLookAheadNextChange CURMaintMarginReq CURMaintMarginReq-C CURMaintMarginReq-S CURNetLiquidation CURNetLiquidationByCurrency CURNetLiquidation-C CURNetLiquidation-S CURPreviousDayEquityWithLoanValue CURPreviousDayEquityWithLoanValue-S CUROptionMarketValue CUROptionMarketValue CURRealizedPnL CURSMA CURSMA-S CURStockMarketValue CURTotalCashBalance CURTotalCashValue CURTotalCashValue-C CURTotalCashValue-S CURUnalteredInitMarginReq CURUnalteredMaintMarginReq CURUnrealizedPnL Quando a moeda não for especificado O IBc primeiro procura os valores especificados na moeda BASE e, se não for encontrado, usa o USD como padrão, então você pode usar o GetAccountValue antigo (quotAvailableFundsquot) e retornará o mesmo como GetAccountValue (quotUSDAvailableFundsquot) - porque os fundos disponíveis não estão especificados em moeda base. Se, no entanto, você chamar GetAccountValue (quotTalkalCashBalancequot), será reportado em moeda BASE e pode ser diferente de GetAccountValue (quotUSDTotalCashBalancequot), que representará apenas USD em dinheiro. As diferenças ocorrerão se você tiver posições de caixa em muitas moedas, portanto, a moeda quotbase mostra o total bruto de todas as posições em todas as moedas, como se elas fossem trocadas na moeda base GetExecInfo (string OrderId, campo de string) Esta função recupera o valor do Field of OrderId Ordene na lista de execução o valor numérico ou apurado do Campo solicitado para OrderId. Nulo se nenhum campo ou nenhuma posição disponível disponível Parâmetros: OrderId - string que especifica a ordem (retornada pela função PlaceOrder ou recuperada pelo GetExecList). Campo - um dos nomes das colunas encontrados em quotExecutionsquot page do IB Controller. Por exemplo, quotAvg. Pricequot dá preço médio de compra de determinada segurança, quotFilledquot dá número de contratos de ações preenchidos GetExecList (número Tipo. String Filter) (novo em 1.3.0) Retorna lista separada por vírgulas de ordens da lista de execuções Parâmetros: Tipo - especifica o que deve ser retornado 0 - dá ORDERIDs (atualmente este é o ÚNICO valor aceito) Filtro - quando não está vazio, ele diz a IBc que somente pedidos com status especificado devem ser retornados quando vazios - todos os pedidos da lista pendente são retornados. Símbolos ibc. GetPendingList (0. Preenchido) - retorna a lista separada por vírgulas de símbolos de identificação de pedidos preenchidos completamente ibc. GetPendingList (0.) - lista de devolução de todos os orderIDs presentes na lista quotexecutions Para extrair símbolos da lista, use esse tipo de loop: Para (i 0 (símbolo StrExtract (símbolos, i)) i) printf (Símbolo: símbolo n) execlist ibc. GetExecList (0.) lista todas as ordens da página de execuções execinfo para (i 0 (OId StrExtract (execlist, i)) I) execinfo execinfo Símbolo OID: ibc. GetExecInfo (OID, Symbol) preenchido: ibc. GetExecInfo (OID, preenchido) Média. Preço: ibc. GetExecInfo (OID, preço médio) n Esta função retorna o texto da última cadeia de mensagens de erro que representa a mensagem de erro. Esvaziar no caso de não haver nenhuma mensagem de erro ou não existe tal ordem OrderId - especifica o ID da ordem para consultar as últimas informações de erro. Existe um valor especial que você pode passar: 0 (zero) e tem um significado especial: ele recupera a última mensagem de erro para qualquer ordem. This is exactly this message that appears on the top of the error list in IBController user interface. GetStatus ( string OrderId . optional boolean InclFilled )This function retrieves status of pending order. string that describes the status, it can be: quotNotYetTransmittedquot, quotPreSubmittedquot, quotPendingquot, quotCancelledquot, quotSubmittedquot, quotFilledquot, quotErrorquot (new in 1.0.2), quotInactivequot or empty when matching order was not found Depending on InclFilled field some statuses are intermittient. If InclFilled is not specified or equal to false (zero) then only quotNotYetTransmittedquot, quotPendingquot, quotPreSubmittedquot, quotSubmittedquot statuses are reported consistently. quotCancelledquot and quotFilledquot statuses are intermittient because such orders are removed from pending orders list within one second from cancellingfilling the order (this will change in the future). quotErrorquot status means that there was an error during processing last request to placemodify an order and you can query detailed error information using GetLastError function. If InclFilled is set to True then also statuses of orders listed on quotExecutionsquot list are reported and this means that you can get quotCancelledquot, quotFilledquot, quotErrorquot, quotInactivequot consistently. Note: InclFilled parameter has been introduced in 1.0.8. Parameters: OrderId - string specifying the orderID to be modified (returned by earlier PlaceOrder or ModifyOrder call). GetPositionInfo ( string Ticker . string Field )This function retrieves the value of the Field of Ticker symbol held currently in the portfolio IMPORTANT CHANGE in 1.1.0. the function does NOT report positions with zero sizes anymore the numeric value of the requested Field for Ticker. Null if no field or no such position available Parameters: Ticker - string that specifies the symbol of securitycontract. The symbol should follow the symbology defined in detail at: amibrokerib. html Field - one of column names found in quotPortfolioquot page of IB Controller. For example quotAvg. costquot gives average cost of purchase of given security, quotUnrealized PNLquot gives unrealized profit and loss. This function retrieves the number of sharescontracts of Ticker symbol held currently in the portfolio the number that descibes the currently held position size for Ticker. Positive numbers mean long position, negative numbers mean short position, zero means that given ticker is not held in the portfolio Parameters: Ticker - string that specifies the symbol of securitycontract. The symbol should follow the symbology defined in detail at: amibrokerib. html IsConnected ()This function retrieves the connection status to TWS. 0 - NO connection 1 - connection in progress 2 - means connection OK, no messages 3 - connection OK, but TWS generated some warningerror messages (see quotMessages tab) IsOrderPending ( string OrderId )This function checks if given order is pending (or not yet transmitted). True - if order is still in the pending list, False if order was Filled, cancelled or there is no such order at all Parameters: OrderId - string specifying the orderID to be modified (returned by earlier PlaceOrder or ModifyOrder call). Returns comma-separated symbol list of currently open positions. IMPORTANT CHANGE in 1.1.0. the function does NOT report positions with zero sizes anymore list of open positions and their sizes ibc GetTradingInterface ( IB ) for ( i 0 ( symbol StrExtract ( openpos, i ) ) i ) printf ( Position i tSymbol: symbol tSize: ibc. GetPositionSize( symbol ) n ) Returns comma separated list of orders from pending list Parameters: Type - specifies what should be returned 0 - gives ORDERIDs, 1 gives symbol lists Filter - when not empty it tells IBc that only orders with specified status should be returned when empty - all orders from pending list are returned. symbols ibc. GetPendingList( 0. Pending ) - returns comma separated list of pending order IDs symbols ibc. GetPendingList( 1. Pending ) - returns comma separated list of SYMBOLS that have pending orders symbols ibc. GetPendingList( 0. Error ) - returns list of orderids that have errors symbols ibc. GetPendingList( 0. Cancelled ) - returns cancelled orderids (please keep in mind that cancelled order are automatically removed from the list after few seconds) symbols ibc. GetPendingList( 0. ) - returns list of all orderIDs present in the quotpending listquot (may be pendingerrorcancelledpartially filledsubmitted, etc) To extract symbols from the list use this kind of loop: for ( i 0 ( symbol StrExtract ( symbols, i ) ) i ) printf ( Symbol: symbol n ) CloseAllOpenPositions ( optional string Ticker ) (new in 1.0.8)Sends orders to close all currently open positions. sends MARKET SELLBUY order for each and every LONGSHORT position in the portfolio page - should effectively close all open positions (provided that closing orders will fill correctly), note however that it may happen that these closing orders may fail (for example when markets are closed) New in 1.1.0: now function accepts optional parameter. When it is provided, the function closes positions only on specified ticker. If it is not specified - it operates as previously (closes positions on all symbols). CancelAllPendingOrders ( optional string Ticker ) (new in 1.0.8)Cancels all pending orders Sends cancel for each and every order displayed in the Pending orders page (with the exception of orders with Errors) New in 1.1.0: now function accepts optional parameter. When it is provided, the function cancels orders only of specified ticker. If it is not specified - it operates as previously (cancels all pending orders on all symbols). Transmit ( string OrderID ) (new in 1.0.8)Modifies transmit flag on NotYetTransmitted order Paramters: OrderID - string specifying the orderid returned by PlaceOrder Returns non-zero (true) when orderid has been found on the pending order list and zero otherwise. It does not necesarily mean that transmit was successful. Transmit( orderid) is used to transmit orders previously placed with transmit flag set to false. Transmit internally is handled by calling quotmodify orderquot function (so you dont need to specify the same parameters again) but note that TWS has problems with handling modify requests coming too quickly, so you will NOT be able to call modifytransmit immediatelly after placing order with transmit false. In such cases we recommend using manual trigger that is slow enough not to cause problems. Example: ibc. Transmit( orderid ) This is EXPERIMENTAL function. Suspends the execution for specified number of milliseconds . Please do NOT use this function unless you really have to . because it locks both IBController and AmiBroker for specified period of time and both applications wont respond to user actions (such as mousekeyboard input). If you suspend execution for more than few seconds AmiBroker will complain about OLE server not responding. Example: ibc. Sleep( 1000 ) sleep for 1000 milliseconds 1 second Clears specified display list. where ListNo can be: 0 - pending order list 1 - execution list 2 - portfolio list 3 - account information list 4 - error message list -1 - special meaning (new in 1.3.5) - clear ALL lists ibc. ClearList( 4 ) clears error message list Note that this function only affects the display, it does NOT affect the status of orders. So if you have any active orders the quotpending ordersquot, quotexecutionsquot lists will be re-filled with currently active orders during next status update (usually within fraction of second - so it may not be visually noticeable) It also applies for portfolio and account information lists - they will be re-filled with next account update - usually within few seconds. SetAccount ( string Account ) (new in 1.1.0, changed in 1.3.5) IMPORTANT: Functionality of this function has CHANGED IN 1.3.5 ONLY FOR FA (financial advisor) accounts. Sets active account for next PlaceOrder()ModifyOrder() calls. Note that it is also possible now to specify destination account directly via parameter passed to PlaceOrderModifyOrder instead of relying on SetAccount(). SetAccount() does NOT clear lists anymore and does NOT change viewing account as it did in pre-1.3.5 versions. Clearing execution and pending list was problematic because when switching accounts the information about previously sent orders on different account was lost on FampF accounts. So SetAccount() does not clear lists automatically. If you want to do this, you can call ClearList( -1 ) explicitely. Also this function does NOT change the account which is displayed in the quotaccount informationquot window and quotportfolioquot tabs. To change account displayed in the quotaccount informationquot page and quotportfolioquot tabs use new function SetInfoAccount(). Separation of order and viewing accounts allows directing orders to any account withing changing any views, i. e. you can monitorview quotAllquot account - that displays cumulative information for all FampFFA accounts or any other account while placing orders for other accounts. By default viewing information is the quotALLquot account and in most cases there is no need to change it as it receives updates from all sub-accounts. SetInfoAccount ( string Account ) (new in 1.3.5)This function changes the account which is displayed in the quotaccount informationquot window and quotportfolioquot tabs. It does NOT change account used for orders. Separation of order and viewing accounts allows directing orders to any account withing changing any views, i. e. you can monitorview quotAllquot account - that displays cumulative information for all FampFFA accounts or any other account while placing orders for other accounts. By default viewing information is the quotALLquot account and in most cases there is no need to change it as it receives updates from all sub-accounts. Note that IB uses quotAquot subscript to designate quotAllquot account that is aggregate of all subaccounts. So if your FA account has a number of F1234, you need to add quotAquot suffix to it to get aggregate data: Closes connection to TWS and re-opens it, clears all lists and requeries for pending orders. Essentially gives the same effect as you would achieve by terminating and re-running IB Controller. 1. Placing and transmitting Market Buy Order for 100 shares when MACD crosses above Signal line: Buy Cross ( MACD (), Signal () ) if ( LastValue ( Buy ) ) ibc GetTradingInterface ( IB ) check if we are connected OK if ( ibc. IsConnected() ) check if we do not have already open position on this stock if ( ibc. GetPositionSize( Name () ) 0 ) transmit order ibc. PlaceOrder( Name (), Buy. 100. MKT. 0. 0. Day. True ) 2. Placingmodifying a limit order on current price plus 0.10 but without transmitting it (manual transmit required). This code can be run many times and it will modify existing order as long as it is not transmitted. It uses static variables to store orderId from last run. Buy L gt Ref ( H . - 1 ) buy when prices gap up if ( LastValue ( Buy ) ) ibc GetTradingInterface ( IB ) check if we are connected OK if ( ibc. IsConnected() ) place orders only if we do not have already open position on this symbol if ( ibc. GetPositionSize( Name () ) 0 ) retrieve orderID from previous run, will be empty if no order was placed before OrderID StaticVarGetText ( OrderID Name ()) place or modify the order - dont transmit yet OrderID ibc. ModifyOrder( OrderID, Name (), BUY. 100. LMT. LastValue ( C ) 0.10. 0. Day. False ) store orderID for next run so we know which order to modify StaticVarSetText ( OrderID Name (), OrderID) 3. Placingmodifying manually from Parameters dialog. Code to be applied in Indicator Builder. (Modified to use new features in 1.0.2) This code can be run many times and it will modify existing order as long as it is not transmitted. It uses static variables to store orderId from last run. Param block TriggerOrder ParamTrigger ( Place order. Click here to place order ) Mode ParamToggle ( Mode. Modify existingAlways place new order ) ACT ParamList ( Action. BUYSELLSSHORT ) OT ParamList ( Order Type. MKTLMTSTP ) TIF ParamList ( Time In Force. DAYGTCIOC ) Ticker ParamStr ( Ticker. Name ()) NumShares Param ( Number of Shares. 10. 10. 100. 10 ) LimitPrice LastValue ( C ) Param ( Limit Price offset. 0 ,- 0.1. 0.1. 0.01 ) StopPrice LastValue ( C ) Param ( Stop price offset. 0 ,- 0.1. 0.1. 0.01 ) Transmit ParamToggle ( Transmit. Do NOT transmitTransmit. 0 ) TriggerCancel ParamTrigger ( Cancel Order. Click here to Cancel order ) Msg this variable stores error message text create instance of trading interface ibc GetTradingInterface ( IB ) retrieve orderID from previous run, will be empty if no order was placed before OrderID StaticVarGetText ( OrderID Ticker) if ( TriggerOrder ) check if we are connected OK if ( ibc. IsConnected() ) if ( Mode 1 ) OrderID i f mode set to always new then clear orderid place orders only if we do not have already open position on this symbol place or modify the order - dont transmit yet OrderID ibc. ModifyOrder( OrderID, Ticker, ACT, NumShares, OT, LimitPrice, StopPrice, TIF, Transmit) store orderID for next run so we know which order to modify StaticVarSetText ( OrderID Ticker, OrderID) if ( Mode 1 ) Msg New order has been placed with ID else Msg Order placedmodified with ID Msg Msg OrderID on Now () else Msg Placing order failed because of no connection to TWS if ( TriggerCancel ) if ( OrderId ) if ( ibc. CancelOrder( OrderId ) ) Msg Request to cancel order OrderID sent successfully else Msg Request to cancel order OrderID failed. else Msg Can not cancel order becase OrderID is empty execlist ibc. GetExecList( 0. ) all execinfo for ( i 0 ( OId StrExtract ( execlist, i ) ) i ) execinfo execinfo OID Symbol: ibc. GetExecInfo( OID, Symbol ) Filled: ibc. GetExecInfo( OID, Filled ) Avg. price: ibc. GetExecInfo( OID, Avg. price ) n monitoring code Title Msg nLast TWS message: ibc. GetLastError( 0 ) nAvailable funds: ibc. GetAccountValue( AvailableFunds ) Gross Pos. Value: ibc. GetAccountValue( GrossPositionValue ) nOrderID OrderId nTicker Ticker nAction ACT nShares NumToStr (NumShares, 1.0 ) nOrderType OT nLimitPrice NumToStr (LimitPrice, 1.3 ) nStopPrice NumToStr (StopPrice, 1.3 ) nTimeInForce TIF nTransmit NumToStr (Transmit, 1.0 ) n nGetStatus ibc. GetStatus( OrderID ) nGetPositionSize ibc. GetPositionSize( Ticker ) nIsConnected NumToStr (ibc. IsConnected(), 1.0 ) nExecInfon execinfo 4. Placing bracket order create instance of trading interface ibc GetTradingInterface ( IB ) parentID ibc. PlaceOrder( MSFT. BUY. 1000. LMT. 27. 0. GTC. False ) ibc. PlaceOrder( MSFT. SELL. 1000. LMT. 28. 0. GTC. False . 100. . parentID ) ibc. PlaceOrder( MSFT. SELL. 1000. STP. 26. 26. GTC. True . 100. . parentID ) Note that TRANSMIT flag is set to FALSE on all bracket orders except the last one. This ensures that orders wait until bracket order set is completed. Setting Transmit flag to TRUE on the very last one transmits entire bracket. 5. Iterating through open positions: ibc GetTradingInterface ( IB ) for ( i 0 ( symbol StrExtract ( openpos, i ) ) i ) printf ( Position i tSymbol: symbol tSize: ibc. GetPositionSize( symbol ) n ) 6. Placing OCA group orders: ibc. PlaceOrder( MSFT. SELL. 1000. LMT. 28. 0. GTC. True . 100. . 0. MYGROUP ) ibc. PlaceOrder( MSFT. SELL. 1000. STP. 26. 26. GTC. True . 100. . 0. MYGROUP ) 1) Why IBController has BETA status The reason is simple - because it relies on IB API we have no control upon. You need to be aware of the fact that Interactive Brokers may and actually do change TWS and API quite often and any future changes in the APITWS may produce incompatiblities without any warning. We try to adjust IBController as soon as such incompatibilities surface, but we can only do that quotafter the factquot. Due to this there can be periods when IBController does not work properly with certain version(s) of TWS. That is the only reason why IBController is marked as BETA. 2) What exactly is the OrderID, where is the number stored How does it increment Can we assign our own OrderIDs OrderID is a string that represents the unique order number that is assigned by IB Controller (for orders placed via IB Controller) or TWS (for orders placed in TWS) when you place the order. It is automatically incremented on each NEW order. The implementation takes care that generated ID is unique for given session of TWS. You should NOT assign your own IDs because you may risk generating duplicates that will be rejected by TWS. 3) The IB Interface contains a lot of useful information, can we access this information in afl GetAccountValue() function (introduced in 1.0.2) allows that. 4) IMPORTANT. During development i often quotlosequot my connection to the TWS and cannot get it going again. Under what conditions candoes this happen This is probably caused by placing ModifyOrder calls too often so TWS is not able handle them and sends error messages (quotUnable to modify this order as its still being processedquot) and it results in IsConnected() returning false. This should be addressed by next version. If such thing happens you can simply close IB Controller window. 5) Is it possible to read IB LastBifAsk prices while running a eSignal database Right now there is no access to price data via IBController but maybe in the future 6) Why do we have a PlaceOrder() and a ModifyOrder(), if ModifyOrder can be used in both cases Just for completeness. Indeed ModifyOrder alone would be enough. 7) Can we retrieve the quotExecutionsquot and quotPendingquot page (string) from the IB Controller window, for display on the chart Pending - yes you can retrieve the status of the order while it is on quotPendingquot page using GetStatus. As for quotexecutionquot tab - as it is already described in the read me this is in the works. 8) It appears the startup sequence of TWS and AB is significant, is it Not actually TWS and AB - they are independent. But what is important to run TWS before running IB Controller. If you however have your trading code in indicator then it may be auto-refreshed at AB start and in this individual case you would need to run TWS before AB. Anyway if something fails you can simply close IB controller window and it will re-open automatically and reconnect on next call to GetTradingInterface. 9) When the TWSAB connection is broken during trading, what is the best way to restore it Close IB Controller manually. It will re-open automatically and reconnect on next call to GetTradingInterface. 10) What is the consequence of repeated PlaceOrder() or ModifyOrder() execution due to AB Refresh What happens when, instead of using Cross() with use quotgtquot or quotltquot Franly auto-trading interface is NOT indented to be used in indicators. It is intended to be used in AA window. But if you prefer to run it in IB you can do this too, but then you should check pending orders and check portfolio position size for given symbol not to buy too many shares. To answer your question: multiple PlaceOrder calls will result in multiple orders placed. Multiple ModifyOrder() calls may result in the same (if OrderID is empty) or may just result in updating the values of already exisiting, pending order if you specify correct OrderID of order placed before (see the example 2.) 11 ) A quotclearquot Message button would be nice in the IBc window, i have to scroll down continuously to see the latest message (perhaps last-on-top scrolling) It is already available in version 1.0.2 12) What is the best way to write a single-(user initiated)-execution line of code. this is where the ParamTask() i suggested earlier would come in handy. Use new AFL ParamTrigger function ParamTrigger( quotNamequot, quotButton textquot) - to be used in indicator builder - to create triggers (buttons). If you place ParamTrigger in the indicator code it will create a quotbuttonquot in Parameter dialog that can be pressed. Normally ParamTrigger will return zero (0) but when button in the param window is pressed then it will refresh the chart and ParamTrigger will return 1 (one) for this single execution (further refreshes will return zero, until the button is pressed again) trigger ParamTrigger ( Place Order. Click here to place order ) if ( trigger ) your one-shot code here 13) When placing orders from an indicator (the thing to do in RT trading) and editing the code will result in additional afl executions, how can i prevent randon order placement from the extra passes Parameters and Signals may not be the same as a result of using loops, DLLs, and things. Use static variables as given in example 2 to MODIFY existing order instead of placing many new orders. Or use code given in response to question 10 14) I got an warning from TWS that is treated as error in Pending list. How can I solve that You can put specific TWS code onto quotIgnore listquot (use File-gtError code ignore list to enter codes in comma separated list). Any code entered here will be ignored by Pending List page, but still will be displayed in the messages window. 15) some message in the IBc are not clearprecise in their meaning. Well these messages come from TWS and I have no influence on their wording :-) CHANGES FOR VERSION 1.3.8 removed the workaround introduced in 1.3.5 for symbol translation because it caused problems for symbols like 6EU0-GLOBEX-FUT where symbol is not equal to local symbol less expiration code (EUR vs 6E). Instead symbol translation now relies solely on method introduced in 1.3.6 CHANGES FOR VERSION 1.3.7 GetPositionList() returned empty symbol part for non-stocks. Fixed PlaceOrder failed on Financial advisor accounts when non-master Account was passed in a parameter without preceding SetAccount call. Fixed. CHANGES FOR VERSION 1.3.6 IBController now uses more reliable way to translate from local symbol to TWS symbolexpiry pair based on information sent back by TWS. (It is not as simple as one may think because sometimes local symbol does not contain TWS symbol, so one can not derive TWS symbol from local symbol in general case, for example FESX SEP 10 local symbol translates to ESTX50,20100917, therefore IBController needs to get info from TWS) CHANGES FOR VERSION 1.3.5 New SetInfoAccount( account ) This function changes the account which is displayed in the quotaccount informationquot window and quotportfolioquot tabs. It does NOT change account used for orders. Separation of order and viewing accounts allows directing orders to any account withing changing any views, i. e. you can monitorview quotAllquot account - that displays cumulative information for all FampFFA accounts or any other account while placing orders for other accounts. By default viewing information is the quotALLquot account and in most cases there is no need to change it as it receives updates from all sub-accounts. To workaround recent change in TWS, for futures (FUT) symbol field is set by IBController as localsymbol without expiration monthyear. This is temporary workaround which may be broken by other TWS releases. Tested to work with TWS 907.7Pending OrdersExecutionsPortfolioAccount info tabs now have additional command quotAccountquot that specifies the account given item refers toPlaceOrder and ModifyOrder now accept optional Account parameterThis allows to specify destination account for order for FampFFA IB accounts in single call, instead of relying on SetAccountPlaceOrder sequence. Single-call PlaceOrderModifyOrder with account specification allows to specify account without worrying that other threadsprocesses can switch the account between SetAccount() and PlaceOrder(). Now SetAccount() only sets account for NEXT order(s). It does NOT clear lists anymore and does NOT change viewing accountClearing execution and pending list was problematic because when switching accounts the information about previously sent orders on different account was lost on FampF accounts. So SetAccount() does not clear lists automatically. If you want to do this, you can call ClearList( -1 ) explicitely. Also this function does NOT change the account which is displayed in the quotaccount informationquot window and quotportfolioquot tabs. To change account displayed in the quotaccount informationquot page and quotportfolioquot tabs use new function SetInfoAccount(). Separation of order and viewing accounts allows directing orders to any account withing changing any views, i. e. you can monitorview quotAllquot account - that displays cumulative information for all FampFFA accounts or any other account while placing orders for other accounts. By default viewing information is the quotALLquot account and in most cases there is no need to change it as it receives updates from all sub-accounts. ClearList() method accepts -1 as listno - then it clears ALL lists CHANGES FOR VERSION 1.3.2 fixed compatibility issues with TWS version 904 CHANGES FOR VERSION 1.3.1 added configuration file to support AmiBroker 5.30 trading from chart functionality CHANGES FOR VERSION 1.3.0 added GetExecList and GetExecInfo functions. CHANGES FOR VERSION 1.2.1 The IBc now accepts new symbology convention with 4th part defining currency: SYMBOL-EXCHANGE-TYPE-CURRENCY. When currency is not specified USD is used as default. For more info see amibrokerib. html The IBc also accepts single letter type codes CHANGES FOR VERSION 1.2.0 IBc now allows to define which error codes should be ignored using File-gtError code ignore list upgraded to use latest TWS API 9.41 (tested with latest TWS 885.7, requires at least 879) following TWS API changes ignoreRth and rthOnly flags are removed and replaced with single flag: outsideRTH Quote from TWS DOC interactivebrokersensoftwareapiReleaseNotesapi94.phpibentityllc quotOutsideRTH Flag Replaces quotIgnore Regular Trading Hoursquot and quotRegular Trading Hours Onlyquot Flags Supported in: All API Platforms A new, single order atttibute, bool OutsideRTH(), replaces two flags: ignoreRTH and rthOnly in the Order classstruct. If set to true, this new extended order attribute allows orders to trigger or fill outside of regular trading hours. quot CHANGES FOR VERSION 1.1.1 primaryExchange is now set to empty. This solves quotinvalid symbolquot problem occuring for some accounts during last 2 weeks following apparent changes in IB. CHANGES FOR VERSION 1.1.0 Added handling of error codes 2100, 1100, 1101, 1102, 1300 Financial advisor Account support (FC Issue 69) : Added FA-only fields to PlaceOrderModifyOrder When run on FA account IBc automatically queries for account list and uses quotAllquot account by defaultGetAccountValue now allows to query values separately for each currency. Currency specific values are available using this syntax: CURFieldName where CUR is currency symbol for example: USDAvailableFunds EURAvailableFundsWhen currency is NOT specified IBc first looks for values specified in BASE currency and if not found then uses USD as default, so you can use old-style GetAccountValue(quotAvailableFundsquot) and it will return the same as GetAccountValue(quotUSDAvailableFundsquot) - because there available funds are not specified in base currency. If you however call GetAccountValue(quotTotalCashBalancequot) it will report in BASE currency and it may be different from GetAccountValue(quotUSDTotalCashBalancequot) which will represent USD cash only. Differences will occur if you have cash positions in many currencies so quotbasequot currency shows gross total of all positions in all currencies as if they were exchanged into base currency. added limit of error messages to be displayed (File-gtConfigure)added re-querying for positions after reconnectan option to restartreconnect (File-gtReconnect), new method Reconnect()CancelAllPendingOrders( optional Ticker ) now CancelAllPendingOrders method takes optional parameter Ticker. If it is specified - it cancels orders only for specified symbol. If it is NOT specified - it cancels all orders for ALL symbols. ClearList( iListNo ) method added ClearList( ListNo ) where ListNo can be: 0 - pending order list 1 - execution list 2 - portfolio list 3 - account information list 4 - error message listibc. ClearList( 4 ) clears error message list Note that this function only affects the display, it does NOT affect the status of orders. So if you have any active orders the quotpending ordersquot, quotexecutionsquot lists will be re-filled with currently active orders during next status update (usually within fraction of second - so it may not be visually noticeable) It also applies for portfolio and account information lists - they will be re-filled with next account update - usually within few seconds. CloseAllOpenPositions( optional Ticker ) now CloseAllOpenPosition method takes optional parameter Ticker. If it is specified - it closes positions only for specified symbol. If it is NOT specified - it closes all positions. exchange is reported correctly for non-US stocks in Portfolio pageGetPositionList() - returns only symbols with positions ltgt 0OCA groups support added to PlaceOrderModifyOrderuser-definable port and IP number (File-gtConfigure)SetAccount( AccNo ) - for FA accountsWarning 2107 (Historical Market Data Service inactive) and 2104 (market data OK) is silently ignored now CHANGES FOR VERSION 1.0.8 GetStatus() function now has optional parameter InclFilled GetStatus( string OrderId, optional boolean InclFilled ) when InclFilled is provided and set to true GetStatus function provides statuses for filled, cancelled and error orders that may have been already deleted from pending list. TimeInForce field in PlaceOrderModifyOrder allows now to specify quotGood Till Datequot and quotGood After Timequot datetimes)TimeInForce field in PlaceOrderModifyOrder accepts GTD and GAT specifications GTD - Good Till Date - indicates that the order should remain workign untilthe time and date set. Good Till Date specification GTD YYYYMMDD HH:MM:SS TZONE where: YYYY is 4 digit year, MM is 2 digit month, DD is 2 digit day, HH is 2 digit hour, MM is 2 digit minute, SS is 2 digit second (OPTIONAL), TZONE is time zone (OPTIONAL) After regular TimeInForce specifications (DAY, GTC, GTD) you may add extraGoodAfterTime (GAT) part. GAT part comes AFTER semicolon. It indicates thattrade should be submitted after the time and date set: GAT specifications: DAYGAT YYYYMMDD HH:MM:SS TZONE - day order valid after specified datetime GTCGAT YYYYMMDD HH:MM:SS TZONE - good till canceled order valid after specified time GTD yyyymmdd hh:mm:ss tzoneGAT YYYYYMMDD HH:MM:SS TZONE - GTD order valid after specified time where: YYYY is 4 digit year, MM is 2 digit month, DD is 2 digit day, HH is 2 digit hour, MM is 2 digit minute, SS is 2 digit second (OPTIONAL), TZONE is time zone (OPTIONAL) Note: there must be NO SPACE characted between semicolon and GAT string. ibc. PlaceOrder( MSFT. BUY. 100. LMT. 27. 0. DAYGAT 20051214 18:00:00 GMT. True ) - day limit order good after Dec 14,2005, 18:00 GMT ibc. PlaceOrder( MSFT. BUY. 100. LMT. 27. 0. GTD 20051215 17:00:00 GMTGAT 20051214 18:00:00 GMT. True ) - limit order valid from Dec 14,2005 18:00 to Dec 15,2005 17:00 GMT ibc. PlaceOrder( MSFT. BUY. 100. LMT. 27. 0. GTD 20051215 19:00:00 GMT. True ) - limit order valid from now until Dec 15,2005 19:00 GMT Portfolio page should now display correct exchange for futures (now it uses reqContractDetails to query for exchange string that is not sent via accountUpdates by TWS) new Transmit( orderID ) method Transmit( string orderid )- returns non-zero (true) when orderid has been found on the pending order listand zero otherwise. It does not necesarily mean that transmit was successful. Transmit( orderid) is used to transmit orders previously placed with transmit flag set to false. Transmit internally is handled by calling quotmodify orderquot function (so you dont need to specify the same parameters again) but note that TWS has problems with handling modify requests coming too quickly, so you will NOT be able to call modifytransmit immediatelly after placing order with transmit false. In such cases we recommend using manual trigger that is slow enough not to cause problems. GetPositionList() method added - returns comma separated list of currently open positionslist of open positions and their sizes ibc GetTradingInterface ( IB ) for ( i 0 ( symbol StrExtract ( openpos, i ) ) i ) printf ( Position i tSymbol: symbol tSize: ibc. GetPositionSize( symbol ) n ) GetPendingList( Type, Filter ) - retrieves comma-separated list of orders from pending listwhere: Type - specifies what should be returned 0 - gives ORDERIDs, 1 gives symbol lists Filter - when not empty it tells IBc that only orders with specified status should be returned when empty - all orders from pending list are returned. symbols ibc. GetPendingList( 0. Pending ) - returns comma separated list of pending order IDs symbols ibc. GetPendingList( 1. Pending ) - returns comma separated list of SYMBOLS that have pending orders symbols ibc. GetPendingList( 0. Error ) - returns list of orderids that have errors symbols ibc. GetPendingList( 0. Cancelled ) - returns cancelled orderids (please keep in mind that cancelled order are automatically removed from the list after few seconds) symbols ibc. GetPendingList( 0. ) - returns list of all orderIDs present in the quotpending listquot (may be pendingerrorcancelledpartially filledsubmitted, etc) added experimental Sleep() methodSleep( number Milliseconds ) - suspends the execution for specified number of milliseconds. Please do NOT use this function unless you really have to, because it locksboth IBController and AmiBroker for specified period of time and both applicationswont respond to user actions (such as mousekeyboard input). If you suspendexecution for more than few seconds AmiBroker will complain about OLE server not responding. added CloseAllOpenPositons(), CancelAllPendingOrders methods and Panic buttonCloseAllOpenPositions() method - sends MARKET SELLBUY order for each and every LONGSHORT position in the portfolio page - should effectively close all open positions (provided that closing orders will fill correctly), note however that it may happen that these closing orders may fail (for example when markets are closed) CancelAllPendingOrders - sends cancel for each and every order displayed in the Pending orders page (with the exception of orders with Errors) Panic button in the toolbar - sends CancelAllPendingOrders() and then CloseAllOpenPositions() Bracket orders support. PlaceOrder and ModifyOrder methods have two additional optional parameters: Attributes and ParentIDPlaceOrder( string Ticker, string Action, number Quantity, string Type, number LimitPrice, number StopPrice, string TimeInForce, bool Transmit, optional number TickSize 100, optional string Attributes quotquot, optional string ParentID quotquot Attributes - is a string that allows to specify additional order attributes (comma separated list). Supported attributes: rthOnly - (OBSOLETE NOW in 1.2.0) if specified means that the order will only be filled during RTH this applies to any order type including limit. ignoreRth - (OBSOLETE NOW in 1.2.0) if specified means that order will trigger not only during Regular Trading Hours (RTH), but also in extended trading (preafter market) this applies to stop orders, conditional orders, and alerts it is used by the triggering logic. If not specified (false) orders will trigger ONLY during RTH. allOrNone - fill all or nothing at all eTradeOnly - tra de with electronic quotes only firmQuoteOnly - trade with firm quotes only By default all those flags are INACTIVE (OFF) Example: ibc. PlaceOrder( MSFT. BUY. 1000. LMT. 27. 0. GTD 20051215 19:00:00 GMT. True . 100. allOrNone ) (Note that optional parameter TickSize MUST be specified if you want to use Attributes) ParentID - is a string that specifies parent order identifier (returned by previous PlaceOrder call) allowing you to place BRACKET orders. parentID ibc. PlaceOrder( MSFT. BUY. 1000. LMT. 27. 0. GTC. False ) ibc. PlaceOrder( MSFT. SELL. 1000. LMT. 28. 0. GTC. False . 100. . parentID ) ibc. PlaceOrder( MSFT. SELL. 1000. STP. 0. 26. GTC. True . 100. . parentID ) now IBController does not require API installation CHANGES FOR VERSION 1.0.6 re-compiled with TWS API 8.41 BETA CHANGES FOR VERSION 1.0.5 fixed problem with GetPositionSize() reporting zero for SMART routed symbols in 1.0.4 CHANGES FOR VERSION 1.0.4 fixed symbology used in Order, Status and Porfolio pages so now futures and currencies work nicely added optional TickSize parameter that defines minimum price fluctuation allowed for given symbol (expressed in pips, i. e. 0.0001). For stocks usually 100 (i. e. 0.01), for Forex: 1. automatic reconnect implemented - IBc now attempts to reconnect to IB every 5 seconds when case connection is lost or IB has crashed and was restarted Now works with quotFire OpenOrder on status changequot setting turned off as well as turned on. Order once marked with quotErrorquot status keeps last error message CHANGES FOR VERSION 1.0.3 compiled with TWS API 8.30 added GetPositionInfo method added unlock code dialog (File-gtEnter Unlock code). IBController by default does not transmit orders automatically. Transmission can be enabled by entering unlock code that is made available to the user after accepting the agreement. CHANGES FOR VERSION 1.0.2 IBC: Now pending order list features new status code quoterrorquot and new column: Last error IBC: New toolbar button: auto-cancel orders with errors - when turned on, all orders with errors are cancelled automatically IBC: Error messages now show order id and error code IBC: Repeating messages are now displayed once with appropriate repeat count and last update time IBC: Most recent error messages now appear on the top of the quotmessagequot list, so you dont need to scroll IBC: quotDuplicate order IDquot problem solved Now when TWS sends quotduplicate orderquot message, appropriate order line is marked in IB Controlled as quoterrorquot and such order ID is no longer used. When new ModifyOrder is placed then new order id will be assigned IBC: GetAccountValue function in IB interface CHANGES FOR VERSION 1.0.1 CancelOrder() removes quotNotYetTransmittedquot orders from the pending list IsConnected() funcition now returns integer values 0..3 (not bool) Clear Messages toolbar button added CHANGES FOR VERSION 1.0.0 HOW TO REPORT BUGS If you experience any problem with this beta version please send detailed description of the problem (especially the steps needed to reproduce it) to bugs at amibroker

No comments:

Post a Comment