Monday 21 August 2017

Lmt Forex Formula Download


AmiBroker Auto-Trading interface 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 FAQ 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. Ele também permite cancelar a transferência de pedidos 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 adquirido. 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 data definidas: DAYGAT AAAAMMDD HH: MM: SS TZONE - ordem do dia válida após o horário especificado GTCGAT YYYYMMDD 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 deve ser feita 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 do 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 movimento), para a maioria das moedas: 1 (representa 0.0001 movimentos), se o movimento mínimo for inferior a 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 exclusivas 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 os 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 string 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. False) ibc. PlaceOrder (MSFT. VENDER. 1000. LMT. 28. 0. GTC. False. 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 - outras ordens são canceladas 2 REDUCEWITHBLOCK - outras ordens são reduzidas em tamanho e a proteção de sobrellenado está LIGADA 3 REDUCENONBLOCK - outras ordens são reduzidas em tamanho e a proteção de sobrellenado está DESLIGADA 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, o perfil, o método e a 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 o pedido de 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 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 US $ 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 segurança dada, quotFilledquot dá número de contratos de ações preenchidos GetExecList (número Tipo. Filtro de Cadeia de caracteres) (novo em 1.3.0) Retorna a lista separada por vírgula 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 ao IBc que somente as ordens com status especificado devem ser retornadas quando vazias - todas as ordens da lista pendente são retornadas. Símbolos ibc. GetPendingList (0. Preenchido) - retorna uma lista separada por vírgulas de símbolos de identificação de pedido completamente preenchidos ibc. GetPendingList (0.) - retorna a lista 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, Símbolo) 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. Esta é exatamente essa mensagem que aparece na parte superior da lista de erros na interface do usuário IBController. GetStatus (string OrderId. Boolean opcional InclFilled) Esta função recupera o status da ordem pendente. Seqüência que descreva o status, pode ser: quotNotYetTransmittedquot, quotPreSubmittedquot, quotPendingquot, QuotCancelledquot, quotSubmittedquot, quotFilledquot, quotErrorquot (novo em 1.0.2), quotInactivequot ou vazio quando o pedido correspondente não foi encontrado. Dependendo do campo InclFilled, alguns status são intermittidos. Se InclFilled não for especificado ou igual a falso (zero), então apenas QuotNotYetTransmittedquot, quotPendingquot, quotPreSubmittedquot, quotSubmitado statuss são relatados de forma consistente. QuotCancelledquot e quotFilledquot status são intermittient porque tais ordens são removidas da lista de pedidos pendentes dentro de um segundo de cancelar o preenchimento da ordem (isso mudará no futuro). QuotErrorquot status significa que houve um erro durante o processamento da última solicitação para placemodify um pedido e você pode consultar informações de erro detalhadas usando a função GetLastError. Se InclFilled estiver definido como Verdadeiro, então, os estados dos pedidos listados na lista quotExecutionsquot são relatados e isso significa que você pode obter quotCancelledquot, quotFilledquot, quotErrorquot, quotInactivequot consistentemente. Nota: O parâmetro InclFilled foi introduzido em 1.0.8. Parâmetros: OrderId - string especificando o orderID para ser modificado (retornado pelo anterior PlaceOrder ou ModifyOrder call). GetPositionInfo (string Ticker. String Field) Esta função recupera o valor do símbolo Field of Ticker mantido atualmente no portfólio IMPORTANT CHANGE em 1.1.0. A função NÃO relata posições com zero tamanhos mais o valor numérico do Campo solicitado para Ticker. Nulo se nenhum campo ou nenhuma posição disponível disponível Parâmetros: Ticker - string que especifica o símbolo do contrato de segurança. O símbolo deve seguir a simbologia definida em detalhes em: amibrokerib. html Campo - um dos nomes de coluna encontrados na página QuotPortfolioquot do IB Controller. Por exemplo, quotAvg. Costquot dá o custo médio de compra de segurança dada, o PNLquot realizado ns produz ganhos e perdas não realizados. Esta função recupera o número de contratos de ações do símbolo do Ticker que atualmente contém no portfólio o número que descile o tamanho da posição atualmente mantida no Ticker. Os números positivos significam a posição longa, os números negativos significam posição curta, zero significa que o ticker não é mantido no portfólio Parâmetros: Ticker - string que especifica o símbolo do contrato de segurança. O símbolo deve seguir a simbologia definida em detalhes em: amibrokerib. html IsConnected () Esta função recupera o status da conexão para o TWS. 0 - NÃO conexão 1 - conexão em andamento 2 - significa conexão OK, sem mensagens 3 - conexão OK, mas TWS gerou algumas mensagens de aviso de aviso (consulte a guia quotMessages) IsOrderPending (string OrderId) Esta função verifica se a ordem está pendente (ou ainda não transmitido). Verdadeiro - se a ordem ainda estiver na lista pendente, Falso se o pedido foi preenchido, cancelado ou não há tal ordem. Parâmetros: OrderId - string especificando o ID de ordem a ser modificado (retornado pelo anterior PlaceOrder ou ModifyOrder call). Retorna a lista de símbolos separados por vírgulas das posições atualmente abertas. MUDANÇA IMPORTANTE em 1.1.0. A função não relata posições com zero tamanhos mais lista de posições abertas e seus tamanhos ibc GetTradingInterface (IB) para (i 0 (símbolo StrExtract (openpos, i)) i) printf (Posição i tSymbol: símbolo tSize: ibc. GetPositionSize ( Símbolo) n) Retorna a lista de ordens separadas por vírgulas da lista pendente Parâmetros: Tipo - especifica o que deve ser retornado 0 - fornece ORDERIDs, 1 fornece listas de símbolos Filtro - quando não está vazio, ele diz a IBc que somente pedidos com status especificado devem ser retornados quando vazios - todas as ordens da lista pendente são devolvidas. Símbolos ibc. GetPendingList (0. Pendente) - retorna a lista separada por vírgulas dos símbolos de identificação de pedidos pendentes ibc. GetPendingList (1. Pendente) - retorna a lista separada por vírgulas de SÍMBOLOS com símbolos de pedidos pendentes ibc. GetPendingList (0. Error) - lista de devolução Dos ordenadores que têm símbolos de erros ibc. GetPendingList (0. Cancelado) - retorna pedidos cancelados (lembre-se de que a ordem cancelada é removida automaticamente da lista depois de alguns segundos) símbolos ibc. GetPendingList (0.) - lista de devolução de todos os IDs de pedidos Presente no quotpending listquot (pode ser pendingerrorcancelledpartially filledsubmitted, etc.) Para extrair símbolos da lista use este tipo de loop: for (i 0 (símbolo StrExtract (symbols, i)) i) printf (Símbolo: símbolo n) CloseAllOpenPositions (opcional Ticker string) (novo em 1.0.8) Envia ordens para fechar todas as posições atualmente abertas. Envia a ordem MARKET SELLBUY para cada posição LONGSHORT na página da carteira - deve efetivamente fechar todas as posições abertas (desde que as ordens de fechamento sejam preenchidas corretamente), observe que pode acontecer que essas ordens de fechamento possam falhar (por exemplo, quando os mercados estão fechados ) Novo no 1.1.0: agora a função aceita o parâmetro opcional. Quando é fornecido, a função fecha as posições apenas no ticker especificado. Se não for especificado - funciona como anteriormente (fecha posições em todos os símbolos). CancelAllPendingOrders (ticker de string opcional) (novo em 1.0.8) Cancela todas as ordens pendentes Envios cancelar para cada ordem exibida na página Pedidos pendentes (com exceção de pedidos com erros) Novo em 1.1.0: agora a função aceita o parâmetro opcional . Quando é fornecido, a função cancela pedidos apenas do ticker especificado. Se não for especificado - funciona como anteriormente (cancela todas as ordens pendentes em todos os símbolos). Transmitir (string OrderID) (novo em 1.0.8) Modifica o sinalizador de transmissão na ordem NotYetTransmitted Parâmetros: OrderID - string especificando o orderid retornado por PlaceOrder Retorna não-zero (true) quando orderid foi encontrado na lista de pedidos pendentes e zero caso contrário. Não significa necessariamente que a transmissão tenha sido bem sucedida. Transmit (orderid) é usado para transmitir ordens previamente colocadas com o sinalizador de transmissão definido como falso. Transmitir internamente é processado chamando a função quotmodify orderquot (então você não precisa especificar os mesmos parâmetros novamente), mas note que o TWS tem problemas com o tratamento de pedidos de modificação que vem muito rápido, então você NÃO poderá chamar o modifytransmit imediatamente após colocar o pedido com transmissão falso. Nesses casos, recomendamos usar o gatilho manual que seja lento o suficiente para não causar problemas. Exemplo: ibc. Transmit (orderid) Esta é função EXPERIMENTAL. Suspende a execução por um número especificado de milissegundos. NÃO use esta função, a menos que você realmente precise. Porque ele bloqueia o IBController e o AmiBroker por um período de tempo especificado e ambas as aplicações não responderão às ações do usuário (como a entrada do mousekeyboard). Se você suspender a execução por mais de alguns segundos, o AmiBroker irá reclamar sobre o servidor OLE não responder. Exemplo: ibc. Sleep (1000) durma durante 1000 milissegundos 1 segundo Limpa a lista de exibição especificada. Onde ListNo pode ser: 0 - lista de pedidos pendentes 1 - lista de execução 2 - lista de portfólio 3 - lista de informações da conta 4 - lista de mensagens de erro -1 - significado especial (novo em 1.3.5) - limpe TODAS as listas ibc. ClearList (4) Limpa a lista de mensagens de erro Observe que esta função afeta somente o visor, NÃO afetará o status dos pedidos. Então, se você tiver quaisquer ordens ativas, as ordens quotpendentes, as listas de citações serão recarregadas com ordens atualmente ativas durante a próxima atualização de status (geralmente dentro da fração de segundo - por isso pode não ser visivelmente perceptível). Também se aplica a listas de informações de portfólio e conta - eles serão recarregados com a próxima atualização da conta - geralmente dentro de alguns segundos. SetAccount (string Account) (novo em 1.1.0, alterado em 1.3.5) IMPORTANTE: A funcionalidade desta função CHANGOU EM 1.3.5 SOMENTE PARA contas de FA (consultor financeiro). Define a conta ativa para as chamadas próximas do PlaceOrder () ModifyOrder (). Observe que também é possível agora especificar a conta de destino diretamente através do parâmetro passado para PlaceOrderModifyOrder em vez de confiar em SetAccount (). SetAccount () NÃO limpa mais as listas e NÃO altera a conta de visualização como fez nas versões anteriores a 1.3.5. A compensação da execução e da lista pendente foi problemática porque, ao mudar de conta, as informações sobre ordens enviadas anteriormente em conta diferente foram perdidas nas contas FampF. Portanto, SetAccount () não limpa listas automaticamente. Se você quiser fazer isso, você pode chamar ClearList (-1) explicitamente. Além disso, esta função NÃO altera a conta que é exibida na janela de informações do quotaccount e nas guias quotportfolioquot. Para alterar a conta exibida na página de informações do quotaccount e quotportfolioquot, use a nova função SetInfoAccount (). A separação de contas de ordem e exibição permite dirigir ordens para qualquer conta com a alteração de qualquer visualização, ou seja, você pode monitorar quotAllquot account - que exibe informações cumulativas para todas as contas FampFFA ou qualquer outra conta ao fazer pedidos para outras contas. Por padrão, as informações de exibição são a conta quotALLquot e, na maioria dos casos, não é necessário alterá-la à medida que recebe as atualizações de todas as subcontas. SetInfoAccount (string Account) (novo em 1.3.5) Esta função altera a conta que é exibida na janela de informações do quotaccount e as guias quotportfolioquot. NÃO muda a conta usada para pedidos. A separação de contas de ordem e exibição permite dirigir ordens para qualquer conta com a alteração de qualquer visualização, ou seja, você pode monitorar quotAllquot account - que exibe informações cumulativas para todas as contas FampFFA ou qualquer outra conta ao fazer pedidos para outras contas. Por padrão, as informações de exibição são a conta quotALLquot e, na maioria dos casos, não é necessário alterá-la à medida que recebe as atualizações de todas as subcontas. Observe que o IB usa o subtítulo quotAquot para designar a conta quotAllquot que é agregado de todas as subcontas. Portanto, se sua conta FA tiver um número de F1234, você precisa adicionar quotAquot sufixo para obter dados agregados: Fecha a conexão com o TWS e o reabre, limpa todas as listas e consultas para pedidos pendentes. Essencialmente, dá o mesmo efeito que você conseguiria ao encerrar e reinstalar o IB Controller. 1. Colocação e transmissão da ordem de compra do mercado para 100 partes quando o MACD cruza acima Linha de sinal: Comprar Cruz (MACD (), Sinal ()) se (LastValue (Comprar)) ibc GetTradingInterface (IB) verifique se estamos conectados OK se (ibc. IsConnected ()) verifique se não temos posição aberta neste estoque se (ibc. GetPositionSize (Name ()) 0) transmitem a ordem ibc. PlaceOrder (Name (), Buy. 100. MKT. 0. 0. Day . Verdadeiro) 2. Colocando a modificação de uma ordem de limite no preço atual mais 0,10, mas sem transmissão (é necessária a transmissão manual). Este código pode ser executado muitas vezes e irá modificar a ordem existente, desde que não seja transmitida. Ele usa variáveis ​​estáticas para armazenar orderId da última execução. Compre L gt Ref (H. - 1) compre quando os preços se estendem se (LastValue (Buy)) ibc GetTradingInterface (IB) verifique se estamos conectados OK se (ibc. IsConnected ()) faça pedidos apenas se não tivermos já Posição de abertura neste símbolo se (ibc. GetPositionSize (Name ()) 0) recuperar orderID da execução anterior, estará vazio se nenhuma ordem foi colocada antes de OrderID StaticVarGetText (OrderID Name ()) coloque ou modifique a ordem - não transmita ainda OrderID Ibc. ModifyOrder (OrderID, Name (), BUY. 100. LMT. LastValue (C) 0.10. 0. Day. False) store orderID para a próxima execução, então sabemos qual ordem modificar StaticVarSetText (OrderID Name (), OrderID) 3 . Colocando a modificação manualmente a partir do diálogo Parâmetros. Código a ser aplicado no Indicator Builder. (Modificado para usar novos recursos em 1.0.2) Este código pode ser executado muitas vezes e ele irá modificar a ordem existente, desde que não seja transmitido. Ele usa variáveis ​​estáticas para armazenar orderId da última execução. Bloco de parametros TriggerOrder ParamTrigger (Coloque o pedido. Clique aqui para fazer o pedido) Modo ParamToggle (Modo. Modificar existingAlways colocar nova ordem) ACT ParamList (Action. BUYSELLSSHORT) OT ParamList (Order Type. MKTLMTSTP) TIF ParamList (Time In Force. DAYGTCIOC) Ticker ParamStr (Ticker. Name ()) NumShares Param (Número de Ações. 10. 10. 100. 10) LimitPrice LastValue (C) Param (Limit Price offset. 0, - 0.1. 0.1. 0.01) StopPrice LastValue (C) Param ( Parar o deslocamento do preço. 0, - 0.1. 0.1. 0.01) Transmit ParamToggle (Transmitir. NÃO TRANSFERE TRANSMISSÃO. 0) TriggerCancel ParamTrigger (Cancelar pedido. Clique aqui para cancelar a ordem) Msg esta variável armazena mensagem de erro texto criar instância de interface de negociação ibc GetTradingInterface (IB) recupera o orderID da execução anterior, ficará vazio se nenhuma ordem foi colocada antes de OrderID StaticVarGetText (OrderID Ticker) se (TriggerOrder) verificar se estamos conectados OK if (ibc. IsConnected ()) if (Mode 1) OrderID i Modo F configurado para sempre novo, em seguida, limpe as encomendas de pedidos somente se não tivermos posição aberta neste local de símbolos ou modifique a ordem - não transmite ainda OrderID ibc. ModifyOrder (OrderID, Ticker, ACT, NumShares, OT, LimitPrice, StopPrice , TIF, Transmit) store orderID para a próxima execução, então sabemos qual ordem modificar StaticVarSetText (OrderID Ticker, OrderID) se (Modo 1) Msg Nova ordem foi colocada com ID else Msg Ordem putmodified com ID Msg Msg OrderID on Now () Else Msg A ordem de colocação falhou devido a nenhuma conexão com o TWS se (TriggerCancel) se (OrderId) se (ibc. CancelOrder (OrderId)) Pedido de Mensagem para cancelar a ordem OrderID enviada com êxito mais Msg Pedido para cancelar a ordem OrderID falhou. Else Msg Não é possível cancelar a ordem porque o OrderID está vazio execlist ibc. GetExecList (0.) todo 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 código de monitoração Título Msg nLast TWS mensagem: ibc. GetLastError (0) nActividades disponíveis: 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 amibrokerThe Snake Trading System - Forex Strategies - Forex Resources - Forex Trading-free forex trading signals and FX Forecast 461 The Snake Trading System ALL INDICATORS REPAINT For each indicators, there are a max number of bars within the signal can be repainted, it depends on how many bars the signal is calculated. If its calculated on the last 3 bars, the signal behind the fourth bar cant repaint. If the signail is calculated on the last bar only, it repaint the current open bar only, and you can trade the signal at the closing of the bar. Improperly, theyre called non-repainting indicators. Most indicators wich gives signails to EA (Auto-Trading systems, wich needs only clear signals) works this way, but this is not necessarily the best way to build an indicator for a discrtetional trading system. In a Discretional Trading Stystem repainting is a problem too. You cant have feeling with disappearing arrows, lines and dots Luckly, human eye can filter good and bad signals quite easily, using other indicators monitoring different paramenters. Sometimes, in a trading system . is better let the Trading system give you some fast signals, in addition to other lagged indicator, stronger. Share your opinion, can help everyone to understand the forex strategy.

No comments:

Post a Comment