Neo traderBot

Neo traderBot

Você sabia?

A NeoTraderBot é a primeira comunidade aberta no Brasil com foco em compartilhar informações sobre automatização de estratégias

leaf leftleaf right
Notifications
Clear all

[Solucionado] Apenas 1 movimento do Stop Loss e 1 ordem por vez

8 Posts
3 Usuários
0 Reactions
190 Visualizações
(@rogerioes)
Membro ativo
Registrou: 2 anos atrás
Posts: 5
Iniciador do tópico  

Grande Johnathas, tudo bem fera ? 

Poderia me ajudar ?

Meu código funciona, e bem simples por agora, mas estou com dificuldades dele fazer apenas 1 ordem por vez e eu gostaria de fazer o Stop mover apenas 1 vez, ja estou 3 dias tentando tirar parte dos Snippets mas não estou conseguindo 

A ideia do Stop seria, andou 7 pontos na direção do Gain, ele move o Stop para 1 pontos positivo, move o Stop apenas 1 vez, depois ou volta para o Stop de 1 Ponto ou para o Alvo

Vou colocar o código completo aqui ( ele esta no começo ainda, futuramente pretendo acrescentar mais informações no sinal de compra e venda ) 

var
  SinalC,SinalV        : Boolean;
  EntradaC,StopC,AlvoC : Real;
  EntradaV,StopV,AlvoV : Real;
begin
  SinalV := (Abertura[1] < Fechamento[1]) e (Abertura > Fechamento) e (Maxima[1] <= Maxima) e (Minima <= Minima[1]);
  SinalC := (Abertura[1] > Fechamento[1]) e (Abertura < Fechamento) e (Maxima[1] <= Maxima) e (Minima <= Minima[1]);
  Se SinalC then
    PaintBar(clVerde);
  Se SinalV then
    PaintBar(clVermelho);
  Se (BuyPosition = 0) e (SellPosition = 0) then
    begin
      Se SinalC then
        begin
          EntradaC := Close;
          StopC := Low;
          AlvoC := Close +(Close - Low);
          BuyStop(EntradaC,EntradaC);
          SellToCoverLimit(AlvoC);
          SellToCoverStop(StopC,StopC);
        end;
      Se SinalV then
        begin
          EntradaV := Close;
          StopV := High;
          AlvoV := Close - (High - Close);
          SellShortStop(EntradaV,EntradaV);
          BuyToCoverLimit(AlvoV);
          BuyToCoverStop(StopV,StopV);
        end;
    end;
  se (BuyPosition > 0) then
    begin 
      SellToCoverLimit(AlvoC);
      SellToCoverStop(StopC,StopC);
      Se (Low <= StopC) then
        SellToCoverAtMarket;
    end;
  Se (SellPosition > 0) then
    begin
      BuyToCoverLimit(AlvoV);
      BuyToCoverStop(StopV,StopV);
     
      Se (High >= StopV) then
        BuyToCoverAtMarket;
    end;
  Se time > 1720 then
    closeposition;
end;

   
Citar
(@admin)
Membro Admin
Registrou: 2 anos atrás
Posts: 216
 

Oi @rogerioes!

 

          Uma técnica de stoploss que se aproxima muito do que deseja é o Stop com Breakeven. A diferença é que ao invés de levar o stop para o preço de abertura, você quer garantir ao menos 1 ponto de lucro (presumo que esteja operado mini-dólar).

          O que fiz então foi pegar o código do stoploss com breakeven e adaptar a sua necessidade, conforme segue abaixo.

          Substitui as aberturas de posição para ordens a mercado para não complicar muito na sua primeira versão.

          Sugiro você buscar entender como todo o código está se relacionando (o bloco de sinais -> execução de ordens -> Stop Breakeven) para que você consiga evoluir com a próxima melhoria que deseja.

           Você verá que o ponto de lucro no breakeven eu quando atribuo o fPrecoStop somando 1 ao preço de abertura de posição.

 

Abs! 

 

const
 cStopOffsetEmTicks = 10;
 cBreakevenEmTicks = 14;

input
  bModuloAutomacao(false);
  iHorarioEncerramentoDaytrade(1720);

var
  SinalC,SinalV        : Boolean;
  EntradaC,StopC,AlvoC : Real;
  EntradaV,StopV,AlvoV : Real;

  fPrecoStop, fPrecoAlvo, fPrecoStopOffset: float;
  bConfigurouRiscoInicial: boolean;
  bPosicionado: boolean;

begin
  SinalC := false;
  SinalV := false;

  //Sinais de abertura de posição
  SinalV :=   (Abertura[1] < Fechamento[1]) 
            e (Abertura > Fechamento) 
            e (Maxima[1] <= Maxima) 
            e (Minima <= Minima[1]);

  SinalC :=   (Abertura[1] > Fechamento[1]) 
            e (Abertura < Fechamento) 
            e (Maxima[1] <= Maxima) 
            e (Minima <= Minima[1]);
  
  //Coloração de barras de entrada
  Se SinalC and not hasPosition then
    PaintBar(clGreen);
  Se SinalV and not hasPosition then
    PaintBar(clVermelho);
  
  //Abertura de posição e definição de alvo e stop
  Se SinalC and not hasPosition then
    begin
      StopC := Low;
      AlvoC := Close + (Close - Low);
      BuyAtMarket;
    end;

  Se SinalV and not hasPosition then
    begin
      StopV := High;
      AlvoV := Close - (High - Close);
      SellShortAtMarket;
    end;


  //Código responsável pela manutenção das ordens de stoploss e take profit
  if isBought then
  begin
    if Not bConfigurouRiscoInicial then
    begin
      //
      fPrecoStop := StopC;
      fPrecoAlvo := AlvoC;
      fPrecoStopOffset := fPrecoStop - cStopOffsetEmTicks*MinPriceIncrement;
      bConfigurouRiscoInicial := true;
    end;

    if Close >= (BuyPrice + cBreakevenEmTicks*MinPriceIncrement) then
    begin
      fPrecoStop := BuyPrice + 1;
      fPrecoStopOffset := fPrecoStop-cStopOffsetEmTicks*MinPriceIncrement;
    end;

    if Not bModuloAutomacao then
    begin
      SellToCoverStop(fPrecoStop,fPrecoStopOffset);
      if isBought then SellToCoverLimit(fPrecoAlvo);
    end
    else
    begin
      SellShortStop(fPrecoStop,fPrecoStopOffset);
      if isBought then SellShortLimit(fPrecoAlvo);
    end;
  end;

  //Código responsável pela manutenção das ordens de stoploss e take profit
  if isSold then
  begin
    if Not bConfigurouRiscoInicial then
    begin
      fPrecoStop := StopV;
      fPrecoAlvo := AlvoV;
      fPrecoStopOffset := fPrecoStop + cStopOffsetEmTicks*MinPriceIncrement;
      bConfigurouRiscoInicial := true;
    end;

    if Close <= (SellPrice - cBreakevenEmTicks*MinPriceIncrement) then
    begin
      fPrecoStop := SellPrice - 1;
      fPrecoStopOffset := fPrecoStop+cStopOffsetEmTicks*MinPriceIncrement;
    end;

    if Not bModuloAutomacao then
    begin
      BuyToCoverStop(fPrecoStop,fPrecoStopOffset);
      if isSold then BuyToCoverLimit(fPrecoAlvo);
    end
    else
    begin
      BuyStop(fPrecoStop,fPrecoStopOffset);
      if isSold then BuyLimit(fPrecoAlvo);
    end;
  end;


  //Encerra posicao
  if (Time >= iHorarioEncerramentoDaytrade)
  and HasPosition
  then ClosePosition;

  if Not hasPosition and bConfigurouRiscoInicial then bConfigurouRiscoInicial := false;

  bPosicionado := hasPosition;
  // Plot de Stop e Alvo para inspeção visual do código
  if bPosicionado or bPosicionado[1] or bPosicionado[2] then
  begin
    PlotN(1,fPrecoStop);
    PlotN(2,fPrecoStopOffset);
    PlotN(3,fPrecoAlvo);
    SetPlotColor(1,clRed);
    SetPlotColor(2,clRed);
    SetPlotColor(3,clGreen);
    SetPlotStyle(1,psDash);
    SetPlotStyle(2,psDash);
    SetPlotStyle(3,psDash);
    SetPlotWidth(1,2);
    SetPlotWidth(2,2);
    SetPlotWidth(3,2);
  end;

end;












   
ReplyCitar
(@rogerioes)
Membro ativo
Registrou: 2 anos atrás
Posts: 5
Iniciador do tópico  

Fala Johnathas, tudo bem ?
Primeiramente MUITO OBRIGADO 

EU errei na regra do SinalV e SinalC mas já consertei aqui, e também estava dando Loss muito grande pois estava abrindo na primeira vela do dia, também conseguir consertar isso em 99% ( vi pouquíssimas op fechando as 17:06, mas ta de boa )

Com intuito de ajudar os membros aqui, vou postar o código do jeito que modifiquei a sua versão acima

Agora vou trabalhar em duas coisas, vi que tem Loss Gigante pois ele entra em vela muito grande, vou tentar acrescentar aqui no SinalV e SinalC que o tamanho da vela de gatilho deve ser menor que XX pontos, assim ele não entra em velas de 20, 25, 35 pontos

E também vou trabalhar para quando der Sinal de Compra, ele so entrar se o FECHAMENTO das 2 ultimas velas estiver ACIMA da media aritmética de 9 ... e so entrar na venda se o fechamento das 2 ultimas velas estiver ABAIXO da media de 9 

Quando eu ficar isso, vou postar aqui novamente pra galera 

Pessoal, se alguém tiver alguma ideia, vamos modificando e postando aqui 

const
 cStopOffsetEmTicks = 10;
 cBreakevenEmTicks = 14;

input
  bModuloAutomacao(false);
  iHorarioInicioAberturaPosicao(0915);
  iHorarioFimAberturaPosicao(1630);
  iHorarioEncerramentoDaytrade(1650);

var
  SinalC,SinalV        : Boolean;
  EntradaC,StopC,AlvoC : Real;
  EntradaV,StopV,AlvoV : Real;

  fPrecoStop, fPrecoAlvo, fPrecoStopOffset: float;
  bConfigurouRiscoInicial: boolean;
  bPosicionado: boolean;

begin
  SinalC := false;
  SinalV := false;
  bPosicionado := hasPosition;
  if not bPosicionado 
  and (Time >= iHorarioInicioAberturaPosicao)
  and (Time <= iHorarioFimAberturaPosicao)
  then     
  begin
  //Sinais de abertura de posição
  SinalV :=   (Abertura[1] < Fechamento[1]) // Candle[1] Verde
            e (Abertura > Fechamento) // Candle Atual Vermelho 
            e (Maxima[1] <= Maxima) // Pavil Superior do Candle Atual Vermelho maior do que o Pavil Superior do Candle Verde Anterior
            e (Minima[1] >= Minima); // Pavil do Inferior do Candle Atual Vermelho menor do que Pavil Inferior do Candle Verde Anterior

  SinalC :=   (Abertura[1] > Fechamento[1]) //Candle Anterior Vermelho
            e (Abertura < Fechamento) // Clandle Atual Vermelho 
            e (Maxima[1] <= Maxima)   // Pavil Superior do Candle Atual Verde maior do que o Pavil Superior do Candle Vermelho Anterior
            e (Minima[1] >= Minima);  // Pavil Inferior do Candle Atual Verde menor do que o Pavil Inferior do Candle Vermelho Anterior
  end;
  //Coloração de barras de entrada
  Se SinalC and not hasPosition then
    PaintBar(clGreen);
  Se SinalV and not hasPosition then
    PaintBar(clVermelho);
  
  //Abertura de posição e definição de alvo e stop
  Se SinalC and not hasPosition then
    begin
      StopC := Low;
      AlvoC := Close + (Close - Low);
      BuyAtMarket;
    end;

  Se SinalV and not hasPosition then
    begin
      StopV := High;
      AlvoV := Close - (High - Close);
      SellShortAtMarket;
    end;


  //Código responsável pela manutenção das ordens de stoploss e take profit
  if isBought then
  begin
    if Not bConfigurouRiscoInicial then
    begin
      //
      fPrecoStop := StopC;
      fPrecoAlvo := AlvoC;
      fPrecoStopOffset := fPrecoStop - cStopOffsetEmTicks*MinPriceIncrement;
      bConfigurouRiscoInicial := true;
    end;

    if Close >= (BuyPrice + cBreakevenEmTicks*MinPriceIncrement) then
    begin
      fPrecoStop := BuyPrice + 1;
      fPrecoStopOffset := fPrecoStop-cStopOffsetEmTicks*MinPriceIncrement;
    end;

    if Not bModuloAutomacao then
    begin
      SellToCoverStop(fPrecoStop,fPrecoStopOffset);
      if isBought then SellToCoverLimit(fPrecoAlvo);
    end
    else
    begin
      SellShortStop(fPrecoStop,fPrecoStopOffset);
      if isBought then SellShortLimit(fPrecoAlvo);
    end;
  end;

  //Código responsável pela manutenção das ordens de stoploss e take profit
  if isSold then
  begin
    if Not bConfigurouRiscoInicial then
    begin
      fPrecoStop := StopV;
      fPrecoAlvo := AlvoV;
      fPrecoStopOffset := fPrecoStop + cStopOffsetEmTicks*MinPriceIncrement;
      bConfigurouRiscoInicial := true;
    end;

    if Close <= (SellPrice - cBreakevenEmTicks*MinPriceIncrement) then
    begin
      fPrecoStop := SellPrice - 1;
      fPrecoStopOffset := fPrecoStop+cStopOffsetEmTicks*MinPriceIncrement;
    end;

    if Not bModuloAutomacao then
    begin
      BuyToCoverStop(fPrecoStop,fPrecoStopOffset);
      if isSold then BuyToCoverLimit(fPrecoAlvo);
    end
    else
    begin
      BuyStop(fPrecoStop,fPrecoStopOffset);
      if isSold then BuyLimit(fPrecoAlvo);
    end;
  end;


  //Encerra posicao
  if (Time >= iHorarioEncerramentoDaytrade)
  and HasPosition
  then ClosePosition;

  if Not hasPosition and bConfigurouRiscoInicial then bConfigurouRiscoInicial := false;

  bPosicionado := hasPosition;
  // Plot de Stop e Alvo para inspeção visual do código
  if bPosicionado or bPosicionado[1] or bPosicionado[2] then
  begin
    PlotN(1,fPrecoStop);
    PlotN(2,fPrecoStopOffset);
    PlotN(3,fPrecoAlvo);
    SetPlotColor(1,clRed);
    SetPlotColor(2,clRed);
    SetPlotColor(3,clGreen);
    SetPlotStyle(1,psDash);
    SetPlotStyle(2,psDash);
    SetPlotStyle(3,psDash);
    SetPlotWidth(1,2);
    SetPlotWidth(2,2);
    SetPlotWidth(3,2);
  end;

end;

   
ReplyCitar
(@rogerioes)
Membro ativo
Registrou: 2 anos atrás
Posts: 5
Iniciador do tópico  

Boa Tarde Pessoal,

Como eu disse acima, queria fazer o Robô so entrar se o Candle de Gatilho fosse menor que XX pontos 

Eu conseguir e ja testei, irei atualizar o Código abaixo 

Vou tentar agora fazer ele so entrar Comprado de o Fechamentos dos 2 últimos candles estiver Acima da media aritmética de 9 
E so entrada Vendido se o Fechamento dos 2 últimos candles estiver Abaixo da media aritmética de 9 

Seeee eu conseguir vou postar o código completo aqui, mas terei bastante dificuldade nisso 

Lembrando que a Regra de Entrada do Robô e SIMPLES, mas você pode aproveita a ESTRUTURA do código e inserir a SUA Regra de Entrada 

const
 cStopOffsetEmTicks = 10;
 cBreakevenEmTicks = 14;
 cTamanhoCandle = 10;  // Tamanho total do candle em PONTOS 

input
  bModuloAutomacao(false);
  iHorarioInicioAberturaPosicao(0915);
  iHorarioFimAberturaPosicao(1630);
  iHorarioEncerramentoDaytrade(1650);

var
  SinalC,SinalV        : Boolean;
  EntradaC,StopC,AlvoC : Real;
  EntradaV,StopV,AlvoV : Real;
  TamanhoCandleC, TamanhoCandleV : Boolean;
  ValorMax, ValorMin : Real;

  fPrecoStop, fPrecoAlvo, fPrecoStopOffset: float;
  bConfigurouRiscoInicial: boolean;
  bPosicionado: boolean;

begin
  SinalC := false;
  SinalV := false;
  bPosicionado := hasPosition;
  if not bPosicionado 
  and (Time >= iHorarioInicioAberturaPosicao)
  and (Time <= iHorarioFimAberturaPosicao)
  then     
  begin
  //Sinais de abertura de posição
  SinalV :=   (Abertura[1] < Fechamento[1]) // Candle[1] Verde
            e (Abertura > Fechamento) // Candle Atual Vermelho 
            e (Maxima[1] <= Maxima) // Pavil Superior do Candle Atual Vermelho maior do que o Pavil Superior do Candle Verde Anterior
            e (Minima[1] >= Minima); // Pavil do Inferior do Candle Atual Vermelho menor do que Pavil Inferior do Candle Verde Anterior

  SinalC :=   (Abertura[1] > Fechamento[1]) //Candle Anterior Vermelho
            e (Abertura < Fechamento) // Clandle Atual Vermelho 
            e (Maxima[1] <= Maxima)   // Pavil Superior do Candle Atual Verde maior do que o Pavil Superior do Candle Vermelho Anterior
            e (Minima[1] >= Minima);  // Pavil Inferior do Candle Atual Verde menor do que o Pavil Inferior do Candle Vermelho Anterior

  ValorMax := (High);
  ValorMin := (Low);
  TamanhoCandleC := (ValorMax - ValorMin) < cTamanhoCandle;
  TamanhoCandleV := (ValorMax - ValorMin) > cTamanhoCandle;


  end;
  //Coloração de barras de entrada
  Se SinalC and TamanhoCandleC and not hasPosition then
    PaintBar(clGreen);
  Se SinalV and TamanhoCandleV and not hasPosition then
    PaintBar(clVermelho);
  
  //Abertura de posição e definição de alvo e stop
  Se SinalC and TamanhoCandleC and not hasPosition then
    begin
      StopC := Low;
      AlvoC := Close + (Close - Low);
      BuyAtMarket;
    end;

  Se SinalV and TamanhoCandleV and not hasPosition then
    begin
      StopV := High;
      AlvoV := Close - (High - Close);
      SellShortAtMarket;
    end;


  //Código responsável pela manutenção das ordens de stoploss e take profit
  if isBought then
  begin
    if Not bConfigurouRiscoInicial then
    begin
      //
      fPrecoStop := StopC;
      fPrecoAlvo := AlvoC;
      fPrecoStopOffset := fPrecoStop - cStopOffsetEmTicks*MinPriceIncrement;
      bConfigurouRiscoInicial := true;
    end;

    if Close >= (BuyPrice + cBreakevenEmTicks*MinPriceIncrement) then
    begin
      fPrecoStop := BuyPrice + 1;
      fPrecoStopOffset := fPrecoStop-cStopOffsetEmTicks*MinPriceIncrement;
    end;

    if Not bModuloAutomacao then
    begin
      SellToCoverStop(fPrecoStop,fPrecoStopOffset);
      if isBought then SellToCoverLimit(fPrecoAlvo);
    end
    else
    begin
      SellShortStop(fPrecoStop,fPrecoStopOffset);
      if isBought then SellShortLimit(fPrecoAlvo);
    end;
  end;

  //Código responsável pela manutenção das ordens de stoploss e take profit
  if isSold then
  begin
    if Not bConfigurouRiscoInicial then
    begin
      fPrecoStop := StopV;
      fPrecoAlvo := AlvoV;
      fPrecoStopOffset := fPrecoStop + cStopOffsetEmTicks*MinPriceIncrement;
      bConfigurouRiscoInicial := true;
    end;

    if Close <= (SellPrice - cBreakevenEmTicks*MinPriceIncrement) then
    begin
      fPrecoStop := SellPrice - 1;
      fPrecoStopOffset := fPrecoStop+cStopOffsetEmTicks*MinPriceIncrement;
    end;

    if Not bModuloAutomacao then
    begin
      BuyToCoverStop(fPrecoStop,fPrecoStopOffset);
      if isSold then BuyToCoverLimit(fPrecoAlvo);
    end
    else
    begin
      BuyStop(fPrecoStop,fPrecoStopOffset);
      if isSold then BuyLimit(fPrecoAlvo);
    end;
  end;


  //Encerra posicao
  if (Time >= iHorarioEncerramentoDaytrade)
  and HasPosition
  then ClosePosition;

  if Not hasPosition and bConfigurouRiscoInicial then bConfigurouRiscoInicial := false;

  bPosicionado := hasPosition;
  // Plot de Stop e Alvo para inspeção visual do código
  if bPosicionado or bPosicionado[1] or bPosicionado[2] then
  begin
    PlotN(1,fPrecoStop);
    PlotN(2,fPrecoStopOffset);
    PlotN(3,fPrecoAlvo);
    SetPlotColor(1,clRed);
    SetPlotColor(2,clRed);
    SetPlotColor(3,clGreen);
    SetPlotStyle(1,psDash);
    SetPlotStyle(2,psDash);
    SetPlotStyle(3,psDash);
    SetPlotWidth(1,2);
    SetPlotWidth(2,2);
    SetPlotWidth(3,2);
  end;

end;

   
ReplyCitar
(@rogerioes)
Membro ativo
Registrou: 2 anos atrás
Posts: 5
Iniciador do tópico  

Boa Tarde Pessoal, atualizei o Código consertando alguns bugs 

Sugestões ? 

 

const
 cStopOffsetEmTicks = 6;
 cBreakevenEmTicks = 6;
 cTamanhoCandle = 12;  // Tamanho total do candle em PONTOS 

input
  bModuloAutomacao(false);
  iHorarioInicioAberturaPosicao(0915);
  iHorarioFimAberturaPosicao(1630);
  iHorarioEncerramentoDaytrade(1650);

var
  SinalC,SinalV        : Boolean;
  EntradaC,StopC,AlvoC : Real;
  EntradaV,StopV,AlvoV : Real;
  TamanhoCandleC, TamanhoCandleV : Boolean;
  ValorMax, ValorMin : Real;

  fPrecoStop, fPrecoAlvo, fPrecoStopOffset: float;
  bConfigurouRiscoInicial: boolean;
  bPosicionado: boolean;

begin
  SinalC := false;
  SinalV := false;
  bPosicionado := hasPosition;
  if not bPosicionado 
  and (Time >= iHorarioInicioAberturaPosicao)
  and (Time <= iHorarioFimAberturaPosicao)
  then     
  begin
  //Sinais de abertura de posição
  SinalV :=   (Abertura[1] < Fechamento[1]) // Candle[1] Verde
            e (Abertura > Fechamento) // Candle Atual Vermelho 
            e (Maxima[1] <= Maxima) // Pavil Superior do Candle Atual Vermelho maior do que o Pavil Superior do Candle Verde Anterior
            e (Minima[1] >= Minima); // Pavil do Inferior do Candle Atual Vermelho menor do que Pavil Inferior do Candle Verde Anterior

  SinalC :=   (Abertura[1] > Fechamento[1]) //Candle Anterior Vermelho
            e (Abertura < Fechamento) // Clandle Atual Vermelho 
            e (Maxima[1] <= Maxima)   // Pavil Superior do Candle Atual Verde maior do que o Pavil Superior do Candle Vermelho Anterior
            e (Minima[1] >= Minima);  // Pavil Inferior do Candle Atual Verde menor do que o Pavil Inferior do Candle Vermelho Anterior

  ValorMax := (High);
  ValorMin := (Low);
  TamanhoCandleC := (ValorMax - ValorMin) < cTamanhoCandle;
  TamanhoCandleV := (ValorMax - ValorMin) < cTamanhoCandle;


  end;
  //Coloração de barras de entrada
  Se SinalC and TamanhoCandleC and not hasPosition then
    PaintBar(clGreen);
  Se SinalV and TamanhoCandleV and not hasPosition then
    PaintBar(clVermelho);
  
  //Abertura de posição e definição de alvo e stop
  Se SinalC and TamanhoCandleC and not hasPosition then
    begin
      StopC := Low;
      AlvoC := Close + (Close - Low);
      BuyAtMarket;
    end;

  Se SinalV and TamanhoCandleV and not hasPosition then
    begin
      StopV := High;
      AlvoV := Close - (High - Close);
      SellShortAtMarket;
    end;


  //Código responsável pela manutenção das ordens de stoploss e take profit
  if isBought then
  begin
    if Not bConfigurouRiscoInicial then
    begin
      fPrecoStop := StopC;
      fPrecoAlvo := AlvoC;
      fPrecoStopOffset := fPrecoStop - cStopOffsetEmTicks*MinPriceIncrement;
      bConfigurouRiscoInicial := true;
    end;

    if Low < Low[1] then ClosePosition;
    

    if Close >= (BuyPrice + cBreakevenEmTicks*MinPriceIncrement) then
    begin
      fPrecoStop := BuyPrice + 1;
      fPrecoStopOffset := fPrecoStop-cStopOffsetEmTicks*MinPriceIncrement;
    end;

    if Not bModuloAutomacao then
    begin
      SellToCoverStop(fPrecoStop,fPrecoStopOffset);
      if isBought then SellToCoverLimit(fPrecoAlvo);
    end
    else
    begin
      SellShortStop(fPrecoStop,fPrecoStopOffset);
      if isBought then SellShortLimit(fPrecoAlvo);
    end;
  end;

  //Código responsável pela manutenção das ordens de stoploss e take profit
  if isSold then
  begin
    if Not bConfigurouRiscoInicial then
    begin
      fPrecoStop := StopV;
      fPrecoAlvo := AlvoV;
      fPrecoStopOffset := fPrecoStop + cStopOffsetEmTicks*MinPriceIncrement;
      bConfigurouRiscoInicial := true;
    end;

    if High > High[1] then ClosePosition;

    if Close <= (SellPrice - cBreakevenEmTicks*MinPriceIncrement) then
    begin
      fPrecoStop := SellPrice - 1;
      fPrecoStopOffset := fPrecoStop+cStopOffsetEmTicks*MinPriceIncrement;
    end;

    if Not bModuloAutomacao then
    begin
      BuyToCoverStop(fPrecoStop,fPrecoStopOffset);
      if isSold then BuyToCoverLimit(fPrecoAlvo);
    end
    else
    begin
      BuyStop(fPrecoStop,fPrecoStopOffset);
      if isSold then BuyLimit(fPrecoAlvo);
    end;
  end;


  //Encerra posicao
  if (Time >= iHorarioEncerramentoDaytrade)
  and HasPosition
  then ClosePosition;

  if Not hasPosition and bConfigurouRiscoInicial then bConfigurouRiscoInicial := false;

  bPosicionado := hasPosition;
  // Plot de Stop e Alvo para inspeção visual do código
  if bPosicionado or bPosicionado[1] or bPosicionado[2] then
  begin
    PlotN(1,fPrecoStop);
    PlotN(2,fPrecoStopOffset);
    PlotN(3,fPrecoAlvo);
    SetPlotColor(1,clRed);
    SetPlotColor(2,clRed);
    SetPlotColor(3,clGreen);
    SetPlotStyle(1,psDash);
    SetPlotStyle(2,psDash);
    SetPlotStyle(3,psDash);
    SetPlotWidth(1,2);
    SetPlotWidth(2,2);
    SetPlotWidth(3,2);
  end;

end;

   
ReplyCitar
(@admin)
Membro Admin
Registrou: 2 anos atrás
Posts: 216
 

 Boa noite Rogério!

        Fiz uma alteração no seu código devido a um novo comportamento do ambiente de backtesting, o qual precisa até ser confirmado com a Nelógica se será assim daqui em diante ou se é um bug.

        O problema é que eles alteram o funcionamento do simulador e não falam nada...Vou explicar como era antes e como está agora. 

        Em uma versão beta não muito distante (rsrsrs) quando se abria uma posição em backtesting, as funções isBought e isSold já reconheciam a posição na linha imediatamente posterior à abertura de posição. Na versão beta em que estamos, isso não ocorre mais. Uma vez aberta a posição, o restante do código processado não reconhecerá a posição aberta, isto será feito apenas no próximo processamento.

         No Módulo de automação, o Manual da Nelógica diz que a estratégia é reprocessada quando se abre uma posição para criar as ordens de stop e alvo que forem necessárias. Mas isto não está ocorrendo em backtesting (por mais que eu e várias pessoas tentemos pedir a Nelogica para manter o mesmo comportamento nos dois contextos) e com dados OHLCV de barra fechada o código é novamente executado apenas no fechamento da próxima barra.

          Assim, o stop não estava sendo aplicado no mesmo candle de abertura de posição. Fiz, portanto, um ajuste no seu código para incluir as ordens ToCover quando as posição são abertas, sem verificar se há ou não posição.

 

É preciso paciência com a Nelógica! Se dúvidar, na próxima versão beta, eles inventam outro jeito para o simulador funcionar (e não avisarão!).

 

Grande abs! Espero que ajude aí!

 

const
 cStopOffsetEmTicks = 6;
 cBreakevenEmTicks = 6;
 cTamanhoCandle = 12;  // Tamanho total do candle em PONTOS 

input
  bModuloAutomacao(false);
  iHorarioInicioAberturaPosicao(0915);
  iHorarioFimAberturaPosicao(1630);
  iHorarioEncerramentoDaytrade(1650);

var
  SinalC,SinalV        : Boolean;
  EntradaC,StopC,AlvoC : Real;
  EntradaV,StopV,AlvoV : Real;
  TamanhoCandleC, TamanhoCandleV : Boolean;
  ValorMax, ValorMin : Real;

  fPrecoStop, fPrecoAlvo, fPrecoStopOffset: float;
  bConfigurouRiscoInicial: boolean;
  bPosicionado: boolean;

begin
  SinalC := false;
  SinalV := false;
  bPosicionado := hasPosition;
  if not bPosicionado 
  and (Time >= iHorarioInicioAberturaPosicao)
  and (Time <= iHorarioFimAberturaPosicao)
  then     
  begin
  //Sinais de abertura de posição
  SinalV :=   (Abertura[1] < Fechamento[1]) // Candle[1] Verde
            e (Abertura > Fechamento) // Candle Atual Vermelho 
            e (Maxima[1] <= Maxima) // Pavil Superior do Candle Atual Vermelho maior do que o Pavil Superior do Candle Verde Anterior
            e (Minima[1] >= Minima); // Pavil do Inferior do Candle Atual Vermelho menor do que Pavil Inferior do Candle Verde Anterior

  SinalC :=   (Abertura[1] > Fechamento[1]) //Candle Anterior Vermelho
            e (Abertura < Fechamento) // Clandle Atual Vermelho 
            e (Maxima[1] <= Maxima)   // Pavil Superior do Candle Atual Verde maior do que o Pavil Superior do Candle Vermelho Anterior
            e (Minima[1] >= Minima);  // Pavil Inferior do Candle Atual Verde menor do que o Pavil Inferior do Candle Vermelho Anterior

  ValorMax := (High);
  ValorMin := (Low);
  TamanhoCandleC := (ValorMax - ValorMin) < cTamanhoCandle;
  TamanhoCandleV := (ValorMax - ValorMin) < cTamanhoCandle;


  end;
  //Coloração de barras de entrada
  Se SinalC and TamanhoCandleC and not hasPosition then
    PaintBar(clGreen);
  Se SinalV and TamanhoCandleV and not hasPosition then
    PaintBar(clVermelho);
  
  //Abertura de posição e definição de alvo e stop
  Se SinalC and TamanhoCandleC and not hasPosition then
    begin
      StopC := Low;
      AlvoC := Close + (Close - Low);
      BuyAtMarket;

      fPrecoStop := StopC;
      fPrecoAlvo := AlvoC;
      fPrecoStopOffset := fPrecoStop - cStopOffsetEmTicks*MinPriceIncrement; 
      if Not bModuloAutomacao then
      begin
        SellToCoverStop(fPrecoStop,fPrecoStopOffset);
        if isBought then SellToCoverLimit(fPrecoAlvo);
      end;
    end;

  Se SinalV and TamanhoCandleV and not hasPosition then
    begin
      StopV := High;
      AlvoV := Close - (High - Close);
      SellShortAtMarket;

      fPrecoStop := StopV;
      fPrecoAlvo := AlvoV;
      fPrecoStopOffset := fPrecoStop + cStopOffsetEmTicks*MinPriceIncrement;
      if Not bModuloAutomacao then
      begin
        BuyToCoverStop(fPrecoStop,fPrecoStopOffset);
        if isSold then BuyToCoverLimit(fPrecoAlvo);
      end;
    end;


  //Código responsável pela manutenção das ordens de stoploss e take profit
  if isBought then
  begin
    if Not bConfigurouRiscoInicial then
    begin
      fPrecoStop := StopC;
      fPrecoAlvo := AlvoC;
      fPrecoStopOffset := fPrecoStop - cStopOffsetEmTicks*MinPriceIncrement;
      bConfigurouRiscoInicial := true;
    end;
    

    if Close >= (BuyPrice + cBreakevenEmTicks*MinPriceIncrement) then
    begin
      fPrecoStop := BuyPrice + 1;
      fPrecoStopOffset := fPrecoStop-cStopOffsetEmTicks*MinPriceIncrement;
    end;

    if Not bModuloAutomacao then
    begin
      SellToCoverStop(fPrecoStop,fPrecoStopOffset);
      if isBought then SellToCoverLimit(fPrecoAlvo);
    end
    else
    begin
      SellShortStop(fPrecoStop,fPrecoStopOffset);
      if isBought then SellShortLimit(fPrecoAlvo);
    end;
  end;

  //Código responsável pela manutenção das ordens de stoploss e take profit
  if isSold then
  begin
    if Not bConfigurouRiscoInicial then
    begin
      fPrecoStop := StopV;
      fPrecoAlvo := AlvoV;
      fPrecoStopOffset := fPrecoStop + cStopOffsetEmTicks*MinPriceIncrement;
      bConfigurouRiscoInicial := true;
    end;

    if Close <= (SellPrice - cBreakevenEmTicks*MinPriceIncrement) then
    begin
      fPrecoStop := SellPrice - 1;
      fPrecoStopOffset := fPrecoStop+cStopOffsetEmTicks*MinPriceIncrement;
    end;

    if Not bModuloAutomacao then
    begin
      BuyToCoverStop(fPrecoStop,fPrecoStopOffset);
      if isSold then BuyToCoverLimit(fPrecoAlvo);
    end
    else
    begin
      BuyStop(fPrecoStop,fPrecoStopOffset);
      if isSold then BuyLimit(fPrecoAlvo);
    end;
  end;


  //Encerra posicao
  if (Time >= iHorarioEncerramentoDaytrade)
  and HasPosition
  then ClosePosition;

  if Not hasPosition and bConfigurouRiscoInicial then bConfigurouRiscoInicial := false;

  bPosicionado := hasPosition;
  // Plot de Stop e Alvo para inspeção visual do código
  if bPosicionado or bPosicionado[1] or bPosicionado[2] then
  begin
    PlotN(1,fPrecoStop);
    PlotN(2,fPrecoStopOffset);
    PlotN(3,fPrecoAlvo);
    SetPlotColor(1,clRed);
    SetPlotColor(2,clRed);
    SetPlotColor(3,clGreen);
    SetPlotStyle(1,psDash);
    SetPlotStyle(2,psDash);
    SetPlotStyle(3,psDash);
    SetPlotWidth(1,2);
    SetPlotWidth(2,2);
    SetPlotWidth(3,2);
  end;

end;

   
ReplyCitar
(@rogerioes)
Membro ativo
Registrou: 2 anos atrás
Posts: 5
Iniciador do tópico  

Grande Johnathas,

Acrescentei a seguinte funções 

O Robô so Compra se o fechamento dos 2 últimos Candles for acima da media de 9 e so Vende se o fechamento dos 2 últimos Candles for abaixo da media de 9

Também modifiquei o calculo para mover o Stop, na Compra calculando a Máxima atingida e na Venda calculando a Mínima atingida 

Código COMPLETO abaixo

const
  cStopOffsetEmTicks = 6;
  cBreakevenEmTicks  = 6;
  cTamanhoCandle     = 12;
  // Tamanho total do candle em PONTOS
input
  bModuloAutomacao(false);
  iHorarioInicioAberturaPosicao(0915);
  iHorarioFimAberturaPosicao(1630);
  iHorarioEncerramentoDaytrade(1650);
var
  SinalC,SinalV                          : Boolean;
  EntradaC,StopC,AlvoC                   : Real;
  EntradaV,StopV,AlvoV                   : Real;
  TamanhoCandleC,TamanhoCandleV          : Boolean;
  ValorMax,ValorMin                      : Real;
  fPrecoStop,fPrecoAlvo,fPrecoStopOffset : float;
  bConfigurouRiscoInicial                : boolean;
  bPosicionado                           : boolean;
  vMediaAri                              : Float;
  v2FechaMediaC,v2FechaMediaV            : Boolean;
begin
  SinalC := false;
  SinalV := false;
  vMediaAri := Media(9,Close);
  bPosicionado := hasPosition;
  if not bPosicionado and (Time >= iHorarioInicioAberturaPosicao) and (Time <= iHorarioFimAberturaPosicao) then
    begin
      //Sinais de abertura de posição
      SinalV := (Abertura[1] < Fechamento[1])
      // Candle[1] Verde
      e (Abertura > Fechamento)
      // Candle Atual Vermelho
      e (Maxima[1] <= Maxima)
      // Pavil Superior do Candle Atual Vermelho maior do que o Pavil Superior do Candle Verde Anterior
      e (Minima[1] >= Minima);
      // Pavil do Inferior do Candle Atual Vermelho menor do que Pavil Inferior do Candle Verde Anterior
      SinalC := (Abertura[1] > Fechamento[1])
      //Candle Anterior Vermelho
      e (Abertura < Fechamento)
      // Clandle Atual Vermelho
      e (Maxima[1] <= Maxima)
      // Pavil Superior do Candle Atual Verde maior do que o Pavil Superior do Candle Vermelho Anterior
      e (Minima[1] >= Minima);
      // Pavil Inferior do Candle Atual Verde menor do que o Pavil Inferior do Candle Vermelho Anterior
      ValorMax := (High);
      ValorMin := (Low);
      TamanhoCandleC := (ValorMax - ValorMin) < cTamanhoCandle;
      TamanhoCandleV := (ValorMax - ValorMin) < cTamanhoCandle;
      v2FechaMediaC := (Close[1] > vMediaAri) and (Close > vMediaAri);
      v2FechaMediaV := (Close[1] < vMediaAri) and (Close < vMediaAri);
    end;
  //Coloração de barras de entrada
  Se SinalC and TamanhoCandleC and v2FechaMediaC and not hasPosition then
    PaintBar(clGreen);
  Se SinalV and TamanhoCandleV and v2FechaMediaV and not hasPosition then
    PaintBar(clVermelho);
  //Abertura de posição e definição de alvo e stop
  Se SinalC and TamanhoCandleC and v2FechaMediaC and not hasPosition then
    begin
      StopC := Low;
      AlvoC := Close + (Close - Low);
      BuyAtMarket;
      fPrecoStop := StopC;
      fPrecoAlvo := AlvoC;
      fPrecoStopOffset := fPrecoStop - cStopOffsetEmTicks * MinPriceIncrement;
      if Not bModuloAutomacao then
        begin
          SellToCoverStop(fPrecoStop,fPrecoStopOffset);
          if isBought then
            SellToCoverLimit(fPrecoAlvo);
        end;
    end;
  Se SinalV and TamanhoCandleV and v2FechaMediaV and not hasPosition then
    begin
      StopV := High;
      AlvoV := Close - (High - Close);
      SellShortAtMarket;
      fPrecoStop := StopV;
      fPrecoAlvo := AlvoV;
      fPrecoStopOffset := fPrecoStop + cStopOffsetEmTicks * MinPriceIncrement;
      if Not bModuloAutomacao then
        begin
          BuyToCoverStop(fPrecoStop,fPrecoStopOffset);
          if isSold then
            BuyToCoverLimit(fPrecoAlvo);
        end;
    end;
  //Código responsável pela manutenção das ordens de stoploss e take profit
  if isBought then
    begin
      if Not bConfigurouRiscoInicial then
        begin
          fPrecoStop := StopC;
          fPrecoAlvo := AlvoC;
          fPrecoStopOffset := fPrecoStop - cStopOffsetEmTicks * MinPriceIncrement;
          bConfigurouRiscoInicial := true;
        end;
      if High >= (BuyPrice + cBreakevenEmTicks * MinPriceIncrement) then
        begin
          fPrecoStop := BuyPrice + 1;
          fPrecoStopOffset := fPrecoStop - cStopOffsetEmTicks * MinPriceIncrement;
        end;
      if Not bModuloAutomacao then
        begin
          SellToCoverStop(fPrecoStop,fPrecoStopOffset);
          if isBought then
            SellToCoverLimit(fPrecoAlvo);
        end
      else 
        begin
          SellShortStop(fPrecoStop,fPrecoStopOffset);
          if isBought then
            SellShortLimit(fPrecoAlvo);
        end;
    end;
  //Código responsável pela manutenção das ordens de stoploss e take profit
  if isSold then
    begin
      if Not bConfigurouRiscoInicial then
        begin
          fPrecoStop := StopV;
          fPrecoAlvo := AlvoV;
          fPrecoStopOffset := fPrecoStop + cStopOffsetEmTicks * MinPriceIncrement;
          bConfigurouRiscoInicial := true;
        end;
      if Low <= (SellPrice - cBreakevenEmTicks * MinPriceIncrement) then
        begin
          fPrecoStop := SellPrice - 1;
          fPrecoStopOffset := fPrecoStop + cStopOffsetEmTicks * MinPriceIncrement;
        end;
      if Not bModuloAutomacao then
        begin
          BuyToCoverStop(fPrecoStop,fPrecoStopOffset);
          if isSold then
            BuyToCoverLimit(fPrecoAlvo);
        end
      else 
        begin
          BuyStop(fPrecoStop,fPrecoStopOffset);
          if isSold then
            BuyLimit(fPrecoAlvo);
        end;
    end;
  //Encerra posicao
  if (Time >= iHorarioEncerramentoDaytrade) and HasPosition then
    ClosePosition;
  if Not hasPosition and bConfigurouRiscoInicial then
    bConfigurouRiscoInicial := false;
  bPosicionado := hasPosition;
  // Plot de Stop e Alvo para inspeção visual do código
  if bPosicionado or bPosicionado[1] or bPosicionado[2] then
    begin
      PlotN(1,fPrecoStop);
      PlotN(2,fPrecoStopOffset);
      PlotN(3,fPrecoAlvo);
      SetPlotColor(1,clRed);
      SetPlotColor(2,clRed);
      SetPlotColor(3,clGreen);
      SetPlotStyle(1,psDash);
      SetPlotStyle(2,psDash);
      SetPlotStyle(3,psDash);
      SetPlotWidth(1,2);
      SetPlotWidth(2,2);
      SetPlotWidth(3,2);
    end;
  Plot(vMediaAri);
  SetPlotColor(1,clYellow);
  SetPlotStyle(1,0);
  SetPlotWidth(1,2);
end;

   
ReplyCitar
(@jolysom)
Novo membro
Registrou: 2 anos atrás
Posts: 1
 

@rogerioes para qual tempo gráfico o backtest desse código foi positivo?

No gráfico de 30min foi positivo, mas teve poucas entrada no período de 1 ano.


   
ReplyCitar