public override void RunSolution(GPSolution solution)
        {
            TradeSystem ts = solution.GetPropriedade(ConstsComuns.OBJ_TRADESYSTEM) as TradeSystem;

            ts.name = solution.name;
            Carteira carteira = gpController.RunBackTester(ts, solution.name);

            carteira.monteCarlo.properties = solution;

            float dif = carteira.GetCapital() - carteira.capitalInicial;

            if (dif > 0)
            {
                float?vExist = solution.GetPropriedade(ConstsComuns.OBJ_TOTAL_PROFIT) as float?;
                float v      = vExist == null ? 0 : (float)vExist;
                v += dif;
                solution.SetPropriedade(ConstsComuns.OBJ_TOTAL_PROFIT, v);
            }
            else
            {
                float?vExist = solution.GetPropriedade(ConstsComuns.OBJ_TOTAL_LOSS) as float?;
                float v      = vExist == null ? 0 : (float)vExist;
                v += dif;
                solution.SetPropriedade(ConstsComuns.OBJ_TOTAL_LOSS, v);
            }

            solution.iterations++;
            solution.SetPropriedade(ConstsComuns.OBJ_ITERATIONS, solution.iterations);
            solution.fitnessResult = carteira.monteCarlo.CalcFitness();
        }
        public void FinishStats(FormulaManager fm, Carteira carteira)
        {
            TradeSystem tradeSystem = carteira.tradeSystem;

            if (ERROR_STOP_0)
            {
                fitness -= PENALTY * 100;
                carteira.tradeSystem.AddError("Stop 0");
            }
            if (ERROR_VLR_STOP_ERRADO)
            {
                fitness -= PENALTY * 100;
            }
            if (ERROR_DISTANCIA_SUPERADA > 0)
            {
                fitness -= PENALTY * ERROR_DISTANCIA_SUPERADA * 100;
            }

            //O tradesystem tentou entrar em todo candle... o que é ruim...
            if (tentouEntrarTodoCandle)
            {
                fitness -= PENALTY * 10000;
                carteira.tradeSystem.AddError("Tentou entrar em todo candle (condicao entrada sempre true)");
            }

            //tentou usar um de sizing fora do range 0 a 100
            if (flagSizingForaRange)
            {
                fitness -= PENALTY * 1000;
                carteira.tradeSystem.AddError("Sizing fora do range");
            }



            if (qtdTrades == 0)
            {
                fitness -= PENALTY * 10000f;
                carteira.tradeSystem.AddError("Zero trades Gerados");
            }

            fitness += qtdTradesGanhadores * BONUS * 10f;

            if (qtdTradesGanhadores < QTD_MINIMA_TRADES / 4)
            {
                fitness -= PENALTY * 10000f;
                carteira.tradeSystem.AddWarning("Qtd. Trades Ganhadores muito baixa.");
            }

            bool viciadaCompra = carteira.config.flagCompra && ((tradeSystem.usaStopMovel && clarify.VerificaFormulaViciada(fm, tradeSystem.stopMovelC)) || clarify.VerificaFormulaViciada(fm, tradeSystem.condicaoEntradaC) || clarify.VerificaFormulaViciada(fm, tradeSystem.stopInicialC));
            bool viciadaVenda  = carteira.config.flagVenda && ((tradeSystem.usaStopMovel && clarify.VerificaFormulaViciada(fm, tradeSystem.stopMovelV)) || clarify.VerificaFormulaViciada(fm, tradeSystem.condicaoEntradaV) || clarify.VerificaFormulaViciada(fm, tradeSystem.stopInicialV));

            if (viciadaCompra || viciadaVenda)
            {
                fitness -= PENALTY * 10000f;
                carteira.tradeSystem.AddError("TradeSystem dependendo de números para gerar resultados.");
            }

            //TODO: Rever essa conta... acho que está prejudicando os que começam a dar lucro...

            /* if (global.maxCapital > carteira.capitalInicial)
             * {
             *   float difMaxCapital = (global.maxCapital - carteira.GetCapital()) * 10;
             *   fitness -= difMaxCapital;
             * }*/

            //Conta a variedade nas ações ganhadoras: acerta 2 ações é melhor que 1 ação
            fitness += CalcBonusVariedade(carteira);



            float difCapital = carteira.GetCapital() - carteira.capitalInicial;

            fitness += BONUS * difCapital / 1000;
            if (difCapital <= 0)
            {
                fitness -= PENALTY * 100;
            }

            fitness += VerificaNumerosFormula(carteira);


            int difTrades = QTD_MINIMA_TRADES - qtdTrades;

            if (difTrades > 0)
            {
                fitness -= PENALTY * difTrades * 1000;
                carteira.tradeSystem.AddWarning("Não atingiu a quantidade mínima de trades.");
            }
            else if (difCapital > 0)
            {
                fitness += percAcerto * BONUS * 100;
            }

            /*//só dou bonus de acerto para os que estiverem acima do objetivo de qtd minima de trades
             * if (difTrades == 0)
             * {
             *  FitnessQtdAcoes();
             *  FitnessPercUsoCapital();
             *  fitness += BONUS * percAcerto / 10;
             *  float avgDias = global.getGeral().getAmbasPontas().getTodosTrades().getAvgDias();
             *  //bonus até 50 dias...
             *  if (avgDias < AVG_DIAS_GOAL)
             *  {
             *      fitness += BONUS;
             *  }
             * }
             */



            fitness /= 1000;
        }
Exemple #3
0
        public void TestBacktesterVars()
        {
            Config config = new Config();

            config.capitalInicial = 100000;
            TradeSystem tradeSystem = new TradeSystem(config);

            facade.LoadAtivo("PETR4", 100, Consts.PERIODO_ACAO.DIARIO, "dados/petr4-diario.js", backend.Consts.TIPO_CARGA_ATIVOS.GERA_CANDIDATOS);
            Ativo ativo = facade.GetAtivo("PETR4");

            Assert.IsNotNull(ativo);
            Assert.IsTrue(ativo.candles.Count > 0);

            Candle  candle  = ativo.firstCandle;
            Periodo periodo = candle.periodo;

            BackTester bt = new BackTester(facade, periodo, config, tradeSystem);

            Carteira carteira = bt.carteira;

            Assert.IsNotNull(carteira);
            Assert.IsTrue(carteira.posicoesFechadas.Count == 0);
            Assert.IsTrue(carteira.posicoesAbertas.Count == 0);
            float riscoTotal = carteira.GetRiscoCarteiraPercent(periodo);

            Assert.IsTrue(riscoTotal == 0);
            // carteira.EfetuaEntrada(ativo, periodo, 1, 10, 9, 1);

            //entro com um valor fixo (direto na carteira)
            Posicao posicao = new Posicao(carteira, ativo, 0);

            carteira.posicoesAbertas.Add(ativo, posicao);

            int qtd = 1000;

            posicao.saldo += qtd;
            Operacao oper1 = new Operacao(carteira, candle, 10, 9, qtd, 1, null);

            posicao.operacoesAbertas.Add(oper1);
            float capitalSobRisco = ((10 - 9) * qtd);
            float riscoEsperado   = capitalSobRisco / carteira.GetCapital() * 100;

            carteira.capitalLiq -= oper1.vlrEntrada * oper1.qtd;

            candle.SetValor(FormulaManager.CLOSE, 10);
            carteira.periodoAtual = periodo;
            carteira.AtualizaPosicao();
            Assert.IsTrue(carteira.GetCapital() == 100000, carteira.GetCapital() + "<>" + 100000);
            Assert.IsTrue(carteira.capitalPosicao == 10000, carteira.GetCapital() + "<>" + 10000);
            riscoTotal = carteira.GetRiscoCarteiraPercent(periodo);
            Assert.IsTrue(riscoTotal == riscoEsperado, riscoTotal + "<>" + riscoEsperado);

            //2a operacao
            Operacao oper2 = new Operacao(carteira, candle, 10, 9, qtd, 1, null);

            posicao.operacoesAbertas.Add(oper2);
            posicao.saldo += qtd;
            carteira.AtualizaPosicao();
            carteira.capitalLiq -= oper1.vlrEntrada * oper1.qtd;
            capitalSobRisco     *= 2;
            riscoEsperado        = capitalSobRisco / carteira.GetCapital() * 100;

            Assert.IsTrue(carteira.GetCapital() == 100000, carteira.GetCapital() + "<>" + 100000);
            Assert.IsTrue(carteira.capitalPosicao == 20000, carteira.GetCapital() + "<>" + 20000);
            riscoTotal = carteira.GetRiscoCarteiraPercent(periodo);
            Assert.IsTrue(riscoTotal == riscoEsperado, riscoTotal + "<>" + riscoEsperado);

            tradeSystem.vm.GetVariavel(Consts.VAR_RISCO_TRADE).vlrAtual  = 2;
            tradeSystem.vm.GetVariavel(Consts.VAR_RISCO_GLOBAL).vlrAtual = 5;

            float qtdTrade = carteira.CalculaQtdTrade(100000, 10, 12, periodo);

            Assert.IsTrue(qtdTrade == 980, qtdTrade + "<>" + 980);
        }
Exemple #4
0
        internal void SelectMonteCarlo(int p)
        {
            DataGridViewRowCollection RowsG = frmPrincipal.GetRows("dataGridRuns");
            MonteCarlo mc = RowsG[p].Cells[0].Value as MonteCarlo;

            if (mc == null)
            {
                return;
            }
            Carteira    carteira = RowsG[p].Cells[1].Value as Carteira;
            Estatistica global   = mc.getGlobal();

            CandidatoData candData = new CandidatoData(carteira.tradeSystem, mc.getGlobal(), carteira.GetCapital());

            Describe(candData);

            // global.getGeral().getAmbasPontas().todosTrades.o
            frmPrincipal.ClearRows("dataGridOperacoes");
            IList <Posicao> posicoes      = carteira.posicoesFechadas;
            float           capital       = config.capitalInicial;
            int             contaOperacao = 0;



            DataGridViewRowCollection Rows = frmPrincipal.GetRows("dataGridOperacoes");

            for (int i = 0; i < mc.operacoes.Count; i++)
            {
                Operacao oper    = mc.operacoes[i];
                Posicao  posicao = oper.posicao;
                contaOperacao++;
                int rowLine = Rows.Count - 1;
                Rows.Add();
                int colIndex = 0;
                Rows[rowLine].Cells[colIndex++].Value = oper;
                Rows[rowLine].Cells[colIndex++].Value = contaOperacao;
                Rows[rowLine].Cells[colIndex++].Value = posicao.idPosicao;
                string ativoName = posicao.ativo.name;
                if (ativoName.Contains("%5E"))
                {
                    ativoName = ativoName.Substring(ativoName.IndexOf("%5E") + 3);
                }
                Rows[rowLine].Cells[colIndex++].Value    = ativoName;
                Rows[rowLine].Cells[colIndex++].Value    = oper.candleInicial.periodo;
                Rows[rowLine].Cells[colIndex++].Value    = oper.candleFinal.periodo;
                Rows[rowLine].Cells[colIndex++].Value    = posicao.direcao > 0 ? "Compra" : "Venda";
                Rows[rowLine].Cells[colIndex++].Value    = oper.qtd;
                Rows[rowLine].Cells[colIndex++].Value    = Utils.FormatCurrency(oper.vlrEntrada);
                Rows[rowLine].Cells[colIndex++].Value    = Utils.FormatCurrency(oper.vlrSaida);
                Rows[rowLine].Cells[colIndex++].Value    = Utils.FormatCurrency(oper.vlrStopInicial);
                Rows[rowLine].Cells[colIndex++].Value    = oper.stopado ? "Sim" : "Não";
                Rows[rowLine].Cells[colIndex++].Value    = oper.qtd * oper.vlrEntrada;
                Rows[rowLine].Cells[colIndex++].Value    = oper.GetDif();
                Rows[rowLine].DefaultCellStyle.ForeColor = Color.Black;
                if (oper.GetDif() > 0)
                {
                    Rows[rowLine].DefaultCellStyle.BackColor = Color.Blue;
                    Rows[rowLine].DefaultCellStyle.ForeColor = Color.White;
                }
                if (oper.GetDif() < 0)
                {
                    Rows[rowLine].DefaultCellStyle.BackColor = Color.Red;
                    Rows[rowLine].DefaultCellStyle.ForeColor = Color.White;
                }
                capital += oper.GetDif() - 2 * config.custoOperacao;
                Rows[rowLine].Cells[colIndex++].Value = capital;
                Rows[rowLine].Cells[colIndex++].Value = oper.capitalOnClose;

                //  oper.
            }
        }
Exemple #5
0
        public void UpdateApplication(Carteira carteira, MonteCarlo mC, int countLoops, int totalLoops)
        {
            Application.DoEvents();
            if (totalLoops <= 0)
            {
                totalLoops = 1;
            }
            if (countLoops <= 1)
            {
                _totalDif   = 0;
                _validCount = 0;
            }


            float dif = carteira.GetCapital() - carteira.capitalInicial;

            if (dif != 0)
            {
                _totalDif += dif;
                _validCount++;
            }
            if (_validCount > 0)
            {
                frmPrincipal.SetText("labelAvgDif", "Avg.Dif.:" + Utils.FormatCurrency(_totalDif / _validCount) + " (" + _validCount + ")");
            }



            frmPrincipal.SetText("labelStatus", countLoops + " / " + totalLoops);
            //frmPrincipal.dataSetBacktest.Tables[0].Rows.Add(mC);
            //DataGridViewRow row = new DataGridViewRow();
            //row.Cells.Add(new DataGridViewCell());
            //frmPrincipal.dataGridRuns.Rows.Add(row);
            DataGridViewRowCollection Rows = frmPrincipal.GetRows("dataGridRuns");

            if (Rows == null)
            {
                return;
            }
            int rowLine = Rows.Count - 1;

            Rows.Add();
            int colIndex = 0;

            contaTestes++;
            SubSubDado todosTrades    = mC.getGlobal().geral.getAmbasPontas().todosTrades;
            SubSubDado tradesGanhos   = mC.getGlobal().geral.getAmbasPontas().tradesGanhos;
            SubSubDado tradesPerdidos = mC.getGlobal().geral.getAmbasPontas().tradesPerdidos;

            Rows[rowLine].Cells[colIndex++].Value = mC;
            Rows[rowLine].Cells[colIndex++].Value = carteira;
            Rows[rowLine].Cells[colIndex++].Value = contaTestes;
            Rows[rowLine].Cells[colIndex++].Value = mC.ToString();

            object objIters   = mC.properties.GetPropriedade(UsoComum.ConstsComuns.OBJ_ITERATIONS);
            int    iterations = (objIters == null ? 1 : (int)objIters);


            Rows[rowLine].Cells[colIndex++].Value = iterations;
            Rows[rowLine].Cells[colIndex++].Value = mC.properties.GetPropriedade(UsoComum.ConstsComuns.OBJ_TOTAL_PROFIT) == null ? 0 : (float)mC.properties.GetPropriedade(UsoComum.ConstsComuns.OBJ_TOTAL_PROFIT) / iterations;
            Rows[rowLine].Cells[colIndex++].Value = mC.properties.GetPropriedade(UsoComum.ConstsComuns.OBJ_TOTAL_LOSS) == null ? 0 : (float)mC.properties.GetPropriedade(UsoComum.ConstsComuns.OBJ_TOTAL_LOSS) / iterations;


            Rows[rowLine].Cells[colIndex++].Value = mC.CalcFitness();
            Rows[rowLine].Cells[colIndex++].Value = mC.getCapitalFinal();
            Rows[rowLine].Cells[colIndex++].Value = mC.getMaxCapital();
            Rows[rowLine].Cells[colIndex++].Value = mC.getMinCapital();
            Rows[rowLine].Cells[colIndex++].Value = mC.winLossRatio;
            Rows[rowLine].Cells[colIndex++].Value = mC.qtdTrades;
            Rows[rowLine].Cells[colIndex++].Value = tradesGanhos.nTrades;
            Rows[rowLine].Cells[colIndex++].Value = tradesPerdidos.nTrades;
            Rows[rowLine].Cells[colIndex++].Value = mC.totalGanho;
            Rows[rowLine].Cells[colIndex++].Value = mC.totalPerdido;
            Rows[rowLine].Cells[colIndex++].Value = mC.percAcerto;
            Rows[rowLine].Cells[colIndex++].Value = mC.capitalUsePercent;
            Rows[rowLine].Cells[colIndex++].Value = todosTrades.maxDias;
            Rows[rowLine].Cells[colIndex++].Value = todosTrades.minDias;
            Rows[rowLine].Cells[colIndex++].Value = todosTrades.avgDias;

            if (Rows.Count > config.maxTestes)
            {
                RemovePiorTeste();
            }
        }