private void updateResults(StrategyTesterResult result, int Action, double profit, double profitpip = 0)
        {
            result.total_trades++;
            if (profit > 0)
            {
                result.total_profit_trades++;
                result.TradeResults.Add(1);
                result.pips_won += profitpip;
                if (profitpip > result.pips_won_max)
                {
                    result.pips_won_max = profitpip;
                }
                if (profitpip < result.pips_won_min)
                {
                    result.pips_won_min = profitpip;
                }

                if (Action == 1)
                {
                    result.total_long_trades++;
                    result.total_long_trades_profitable++;
                }
                else
                {
                    result.total_short_trades++;
                    result.total_short_trades_profitable++;
                }
            }
            else
            {
                result.total_loss_trades++;
                result.TradeResults.Add(-1);
                result.pips_loss += profitpip;
                if (profitpip < result.pips_loss_max)
                {
                    result.pips_loss_max = profitpip;
                }
                if (profitpip > result.pips_loss_min)
                {
                    result.pips_loss_min = profitpip;
                }

                if (Action == 1)
                {
                    result.total_long_trades++;
                    result.total_long_trades_loss++;
                }
                else
                {
                    result.total_short_trades++;
                    result.total_short_trades_loss++;
                }
            }

            result.final_balance += profit;
            result.balance_history.Add(result.final_balance);
        }
        public StrategyTesterResult Run()
        {
            #region Initialize variables
            StrategyTesterResult result = new StrategyTesterResult();
            double[]             TS     = new double[n_data - Window + 1];
            double[,] Weights = new double[n_data - Window + 1, Basket.Length + 1];
            List <string> WeightNames = new List <string>(Basket);
            WeightNames.Add("Intercept");
            List <string>    notes  = new List <string>();
            List <TradeInfo> Trades = new List <TradeInfo>();
            List <double[]>  StandardizedWeights = new List <double[]>();
            List <double[]>  NormalizedWeights   = new List <double[]>();
            List <int[]>     TradeSizes          = new List <int[]>();
            #endregion

            #region Fill up initial results
            result.Basket                 = Basket;
            result.window                 = Window;
            result.bandwidth              = Bandwidth;
            result.transactionCost        = TransactionCost;
            result.initialDeposit         = InitialDeposit;
            result.leverage               = Leverage;
            result.maximum_open_positions = MaxOpenPositions;
            result.final_balance          = InitialDeposit;
            result.balance_history        = new List <double>();
            result.balance_history.Add(InitialDeposit);
            #endregion


            for (int i = Window - 1; i < n_data; i++)
            {
                #region Regression
                double[,] xy   = new double[Window, Basket.Length];
                double[,] data = new double[Window, Basket.Length];
                for (int j = 0; j < Window; j++)
                {
                    for (int k = 0; k < Basket.Length; k++)
                    {
                        xy[j, k]   = Price[k, i - j];
                        data[j, k] = Price[k, i - j];
                    }
                }
                double[] w = LinearRegression.Build(xy, Responsevariableindex);
                double[] x = new double[Basket.Length];

                notes.Add(string.Join(",", w));
                for (int j = 0; j < Basket.Length; j++)
                {
                    TS[i - Window + 1]        += w[j] * Price[j, i];
                    Weights[i - Window + 1, j] = w[j];
                    x[j] = Price[j, i];
                }


                //add constant term
                TS[i - Window + 1] += w[Basket.Length];
                Weights[i - Window + 1, Basket.Length] = w[Basket.Length];
                #endregion

                #region Calculate bands
                double sum = 0;
                double sd = 0;
                double mean = 0;
                double upperBand, lowerBand, deviation;

                for (int j = 1; j < Window; j++)
                {
                    sum += LinearRegression.Predict2(data, j, w);
                }
                mean = sum / Window;
                sum  = 0;
                for (int j = 1; j < Window; j++)
                {
                    double val = LinearRegression.Predict2(data, j, w);
                    sum += ((val - mean) * (val - mean));
                }
                sd        = Math.Sqrt(sum / Window);
                deviation = Bandwidth * sd;
                upperBand = mean + deviation;
                lowerBand = mean - deviation;

                #endregion

                #region Locate current and previous positions
                int    current_position  = 0;
                int    previous_position = 0;
                double current_val       = LinearRegression.Predict2(data, 0, w);
                double previous_val      = LinearRegression.Predict2(data, 1, w);

                if (current_val >= upperBand)
                {
                    current_position = 1;
                }
                else if (current_val < upperBand && current_val > mean)
                {
                    current_position = 2;
                }
                else if (current_val <= mean && current_val > lowerBand)
                {
                    current_position = 3;
                }
                else
                {
                    current_position = 4;
                }

                if (previous_val >= upperBand)
                {
                    previous_position = 1;
                }
                else if (previous_val < upperBand && previous_val > mean)
                {
                    previous_position = 2;
                }
                else if (previous_val <= mean && previous_val > lowerBand)
                {
                    previous_position = 3;
                }
                else
                {
                    previous_position = 4;
                }
                #endregion


                //######################### Close open trades #####################################################

                foreach (TradeInfo trade in Trades)
                {
                    double v = LinearRegression.Predict2(data, 0, trade.Coefficients);
                    if (trade.Action == 1)
                    {
                        #region Check Buy Order
                        if (v >= trade.TP)
                        {
                            //TP is hit. Winner :)

                            trade.IsClosed    = true;
                            trade.close_index = i;
                            result.tradedurations.Add(i - trade.open_index);
                            double estimatepips = 0;
                            double profit       = GetProfit(trade, out estimatepips);
                            updateResults(result, 1, profit, estimatepips);

                            if (profit < 0)
                            {
                                result.total_TP_mismatch++;
                            }
                        }
                        else if (v <= trade.SL)
                        {
                            //SL is hit. Loser :(

                            trade.IsClosed    = true;
                            trade.close_index = i;
                            result.tradedurations.Add(i - trade.open_index);

                            double estimatepips = 0;
                            double profit       = GetProfit(trade, out estimatepips);
                            updateResults(result, 1, profit, estimatepips);

                            if (profit > 0)
                            {
                                result.total_SL_mismatch++;
                            }
                        }
                        #endregion
                    }
                    else
                    {
                        #region Check Sell Order
                        if (v <= trade.TP)
                        {
                            //TP is hit. Winner :)

                            trade.IsClosed    = true;
                            trade.close_index = i;
                            result.tradedurations.Add(i - trade.open_index);

                            double estimatepips = 0;
                            double profit       = GetProfit(trade, out estimatepips);
                            updateResults(result, 1, profit, estimatepips);

                            if (profit < 0)
                            {
                                result.total_TP_mismatch++;
                            }
                        }
                        else if (v >= trade.SL)
                        {
                            //SL is hit. Loser :(

                            trade.IsClosed    = true;
                            trade.close_index = i;
                            result.tradedurations.Add(i - trade.open_index);

                            double estimatepips = 0;
                            double profit       = GetProfit(trade, out estimatepips);
                            updateResults(result, 1, profit, estimatepips);

                            if (profit > 0)
                            {
                                result.total_SL_mismatch++;
                            }
                        }
                        #endregion
                    }
                }
                Trades.RemoveAll(trade => trade.IsClosed);


                //################################## Open trade signals ######################################
                if (Trades.Count < MaxOpenPositions)
                {
                    if (previous_position == 1 && current_position == 2)
                    {
                        //Sell order
                        #region Execute sell order
                        double[] c        = LinearRegression.NormalizeWeights(w, x, InversionDirection);
                        int[]    lotsizes = RiskManager.getTradeSizes(c, result.final_balance, Leverage);
                        if (lotsizes != null)
                        {
                            TradeInfo trade = new TradeInfo();
                            trade.Action       = -1;
                            trade.Coefficients = w;
                            trade.IsClosed     = false;
                            trade.TP           = mean;
                            trade.SL           = mean + 2 * deviation;
                            trade.TradeSizes   = lotsizes;
                            trade.open_index   = i;
                            trade.IsClosed     = false;
                            Trades.Add(trade);

                            result.tradesizes.Add(LinearRegression.TotalNormalizedWeights(w, x, InversionDirection));
                            StandardizedWeights.Add(LinearRegression.StandardizeWeights(w, x, InversionDirection));
                            NormalizedWeights.Add(c);
                            TradeSizes.Add(LinearRegression.getTradeSizes(c));
                        }
                        else
                        {
                            result.total_reject_trades++;
                        }
                        #endregion
                    }
                    else if (previous_position == 4 & current_position == 3)
                    {
                        //Buy order
                        #region Execute buy order
                        double[] c        = LinearRegression.NormalizeWeights(w, x, InversionDirection);
                        int[]    lotsizes = RiskManager.getTradeSizes(c, result.final_balance, Leverage);
                        if (lotsizes != null)
                        {
                            TradeInfo trade = new TradeInfo();
                            trade.Action       = -1;
                            trade.Coefficients = w;
                            trade.IsClosed     = false;
                            trade.TP           = mean;
                            trade.SL           = mean - 2 * deviation;
                            trade.TradeSizes   = lotsizes;
                            trade.open_index   = i;
                            trade.IsClosed     = false;
                            Trades.Add(trade);

                            result.tradesizes.Add(LinearRegression.TotalNormalizedWeights(w, x, InversionDirection));
                            StandardizedWeights.Add(LinearRegression.StandardizeWeights(w, x, InversionDirection));
                            NormalizedWeights.Add(c);
                            TradeSizes.Add(LinearRegression.getTradeSizes(c));
                        }
                        else
                        {
                            result.total_reject_trades++;
                        }
                        #endregion
                    }
                }
                //#####################################################################################
            }

            System.Windows.Forms.SaveFileDialog sf = new System.Windows.Forms.SaveFileDialog();
            sf.Filter           = "CSV file|*.csv";
            sf.InitialDirectory = System.Windows.Forms.Application.StartupPath;
            if (sf.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return(result);
            }
            using (System.IO.StreamWriter sw = new StreamWriter(sf.FileName))
            {
                string header = string.Join(",", Basket);
                header = header + "," + header + "," + "Total," + header;
                sw.WriteLine(header);
                for (int i = 0; i < NormalizedWeights.Count; i++)
                {
                    string[] items = new string[Basket.Length * 3 + 1];
                    for (int j = 0; j < Basket.Length; j++)
                    {
                        items[j] = StandardizedWeights[i][j].ToString();
                    }
                    for (int j = 0; j < Basket.Length; j++)
                    {
                        items[Basket.Length + j] = NormalizedWeights[i][j].ToString();
                    }
                    items[Basket.Length * 2] = result.tradesizes[i].ToString();
                    for (int j = 0; j < Basket.Length; j++)
                    {
                        if (TradeSizes[i] == null)
                        {
                            items[Basket.Length * 2 + 1 + j] = "NA";
                        }
                        else
                        {
                            items[Basket.Length * 2 + 1 + j] = TradeSizes[i][j].ToString();
                        }
                    }
                    sw.WriteLine(string.Join(",", items));
                }
                sw.Close();
            }


            result.postMortem();

            //frmPlot plot1 = new frmPlot();
            //plot1.Show();
            //plot1.draw(TS, "", "", "", -1, notes.ToArray());

            //frmPlot plot2 = new frmPlot();
            //plot2.Show();
            //plot2.draw(Weights, WeightNames.ToArray());



            return(result);
        }
        public StrategyTesterResult[,] Run()
        {
            #region Initialize variables
            StrategyTesterResult[,] resultset = new StrategyTesterResult[Basket.Length, 19];
            List <TradeInfo>[,] TRADES        = new List <TradeInfo> [Basket.Length, 19];
            int[,] OpenTradePositionIndex     = new int[Basket.Length, 19];

            #endregion

            #region Fill up initial results
            for (int i = 0; i < Basket.Length; i++)
            {
                for (int j = 0; j < 19; j++)
                {
                    resultset[i, j]        = new StrategyTesterResult();
                    resultset[i, j].Basket = Basket;
                    resultset[i, j].window = Window;
                    resultset[i, j].maximum_open_positions = MaxOpenPositions;
                    resultset[i, j].final_balance          = InitialDeposit;
                    resultset[i, j].balance_history        = new List <double>();
                    resultset[i, j].balance_history.Add(InitialDeposit);
                    resultset[i, j].transactionCost = TransactionCost;
                    resultset[i, j].initialDeposit  = InitialDeposit;
                    resultset[i, j].leverage        = Leverage;
                    TRADES[i, j] = new List <TradeInfo>();
                }
            }
            #endregion


            for (int i = Window - 1; i < n_data; i++)
            {
                #region Regression
                double[,] xy = new double[Window, Basket.Length];
                for (int j = 0; j < Window; j++)
                {
                    for (int k = 0; k < Basket.Length; k++)
                    {
                        xy[j, k] = Price[k, i - j];
                    }
                }
                double[] x = new double[Basket.Length];
                for (int j = 0; j < Basket.Length; j++)
                {
                    x[j] = Price[j, i];
                }

                double[][] W = new double[Basket.Length][];
                for (int j = 0; j < Basket.Length; j++)
                {
                    W[j] = LinearRegression.Build(xy, j);
                }
                #endregion

                for (int j = 0; j < Basket.Length; j++)
                {
                    double[] w = W[j];

                    #region Calculate SD
                    double sum = 0;
                    double sd = 0;
                    double mean = 0;
                    double upperBand, lowerBand, deviation;

                    for (int k = 1; k < Window; k++)
                    {
                        sum += LinearRegression.Predict(Price, i - k, w);
                    }
                    mean = sum / Window;
                    sum  = 0;
                    for (int k = 1; k < Window; k++)
                    {
                        double val = LinearRegression.Predict(Price, i - k, w);
                        sum += ((val - mean) * (val - mean));
                    }
                    sd = Math.Sqrt(sum / Window);
                    #endregion

                    for (int k = 0; k < 19; k++)
                    {
                        List <TradeInfo>     Trades = TRADES[j, k];
                        StrategyTesterResult result = resultset[j, k];
                        result.bandwidth = (k + 1) * 0.25;

                        #region Calculate bands
                        deviation = (k + 1) * 0.25 * sd;
                        upperBand = mean + deviation;
                        lowerBand = mean - deviation;
                        #endregion

                        #region Locate current and previous positions
                        int    current_position  = 0;
                        int    previous_position = 0;
                        double current_val       = LinearRegression.Predict(Price, i, w);
                        double previous_val      = LinearRegression.Predict(Price, i - 1, w);

                        if (current_val >= upperBand)
                        {
                            current_position = 1;
                        }
                        else if (current_val < upperBand && current_val > mean)
                        {
                            current_position = 2;
                        }
                        else if (current_val <= mean && current_val > lowerBand)
                        {
                            current_position = 3;
                        }
                        else
                        {
                            current_position = 4;
                        }

                        if (previous_val >= upperBand)
                        {
                            previous_position = 1;
                        }
                        else if (previous_val < upperBand && previous_val > mean)
                        {
                            previous_position = 2;
                        }
                        else if (previous_val <= mean && previous_val > lowerBand)
                        {
                            previous_position = 3;
                        }
                        else
                        {
                            previous_position = 4;
                        }
                        #endregion

                        #region Trades
                        //######################### Close open trades #####################################################

                        foreach (TradeInfo trade in Trades)
                        {
                            double v = LinearRegression.Predict(Price, i, trade.Coefficients);
                            if (trade.Action == 1)
                            {
                                #region Check Buy Order
                                if (v >= trade.TP)
                                {
                                    //TP is hit. Winner :)

                                    trade.IsClosed    = true;
                                    trade.close_index = i;
                                    result.tradedurations.Add(i - trade.open_index);
                                    double estimatepips = 0;
                                    double profit       = GetProfit(trade, out estimatepips);
                                    updateResults(result, 1, profit, estimatepips);

                                    if (profit < 0)
                                    {
                                        result.total_TP_mismatch++;
                                    }
                                }
                                else if (v <= trade.SL)
                                {
                                    //SL is hit. Loser :(

                                    trade.IsClosed    = true;
                                    trade.close_index = i;
                                    result.tradedurations.Add(i - trade.open_index);

                                    double estimatepips = 0;
                                    double profit       = GetProfit(trade, out estimatepips);
                                    updateResults(result, 1, profit, estimatepips);

                                    if (profit > 0)
                                    {
                                        result.total_SL_mismatch++;
                                    }
                                }
                                #endregion
                            }
                            else
                            {
                                #region Check Sell Order
                                if (v <= trade.TP)
                                {
                                    //TP is hit. Winner :)

                                    trade.IsClosed    = true;
                                    trade.close_index = i;
                                    result.tradedurations.Add(i - trade.open_index);

                                    double estimatepips = 0;
                                    double profit       = GetProfit(trade, out estimatepips);
                                    updateResults(result, 1, profit, estimatepips);

                                    if (profit < 0)
                                    {
                                        result.total_TP_mismatch++;
                                    }
                                }
                                else if (v >= trade.SL)
                                {
                                    //SL is hit. Loser :(

                                    trade.IsClosed    = true;
                                    trade.close_index = i;
                                    result.tradedurations.Add(i - trade.open_index);

                                    double estimatepips = 0;
                                    double profit       = GetProfit(trade, out estimatepips);
                                    updateResults(result, 1, profit, estimatepips);

                                    if (profit > 0)
                                    {
                                        result.total_SL_mismatch++;
                                    }
                                }
                                #endregion
                            }
                        }
                        Trades.RemoveAll(trade => trade.IsClosed);


                        //################################## Open trade signals ######################################
                        if (Trades.Count < MaxOpenPositions)
                        {
                            if (previous_position == 1 && current_position == 2)
                            {
                                //Sell order
                                #region Execute sell order
                                double[] c        = LinearRegression.NormalizeWeights(w, x, InversionDirection);
                                int[]    lotsizes = RiskManager.getTradeSizes(c, result.final_balance, Leverage);
                                if (lotsizes != null)
                                {
                                    TradeInfo trade = new TradeInfo();
                                    trade.Action       = -1;
                                    trade.Coefficients = w;
                                    trade.IsClosed     = false;
                                    trade.TP           = mean;
                                    trade.SL           = mean + 2 * deviation;
                                    trade.TradeSizes   = lotsizes;
                                    trade.open_index   = i;
                                    trade.IsClosed     = false;
                                    Trades.Add(trade);

                                    result.tradesizes.Add(LinearRegression.TotalNormalizedWeights(w, x, InversionDirection));
                                }
                                else
                                {
                                    result.total_reject_trades++;
                                }
                                #endregion
                            }
                            else if (previous_position == 4 & current_position == 3)
                            {
                                //Buy order
                                #region Execute buy order
                                double[] c        = LinearRegression.NormalizeWeights(w, x, InversionDirection);
                                int[]    lotsizes = RiskManager.getTradeSizes(c, result.final_balance, Leverage);
                                if (lotsizes != null)
                                {
                                    TradeInfo trade = new TradeInfo();
                                    trade.Action       = -1;
                                    trade.Coefficients = w;
                                    trade.IsClosed     = false;
                                    trade.TP           = mean;
                                    trade.SL           = mean - 2 * deviation;
                                    trade.TradeSizes   = lotsizes;
                                    trade.open_index   = i;
                                    trade.IsClosed     = false;
                                    Trades.Add(trade);

                                    result.tradesizes.Add(LinearRegression.TotalNormalizedWeights(w, x, InversionDirection));
                                }
                                else
                                {
                                    result.total_reject_trades++;
                                }
                                #endregion
                            }
                        }
                        //#####################################################################################
                        #endregion
                    }
                }
            }

            #region Post Mortem
            for (int i = 0; i < Basket.Length; i++)
            {
                for (int j = 0; j < 19; j++)
                {
                    resultset[i, j].postMortem();
                    resultset[i, j].balance_history = null;
                    resultset[i, j].tradesizes      = null;
                    resultset[i, j].tradedurations  = null;
                }
            }

            #endregion

            return(resultset);
        }
Esempio n. 4
0
        public frmResults(StrategyTesterResult result)
        {
            InitializeComponent();


            string body;

            using (StreamReader sr = new StreamReader(@"..\..\StrategyTester.htm"))
            {
                body = sr.ReadToEnd();
            }



            // set currency format
            string curCulture = System.Threading.Thread.CurrentThread.CurrentCulture.ToString();

            System.Globalization.NumberFormatInfo currencyFormat = new System.Globalization.CultureInfo(curCulture).NumberFormat;
            currencyFormat.CurrencyNegativePattern = 1;



            body = body.Replace("{1}", result.initialDeposit.ToString("C", currencyFormat));
            body = body.Replace("{11}", Math.Round(result.final_balance, 1).ToString("C", currencyFormat));
            body = body.Replace("{12}", result.expected_profit.ToString());
            body = body.Replace("{14}", result.total_trades.ToString());
            body = body.Replace("{15}", result.pips_net.ToString());
            body = body.Replace("{16}", result.estimate_monthly_profit.ToString());
            body = body.Replace("{17}", result.maximum_open_positions.ToString());
            body = body.Replace("{17}", result.maximum_drawdown.ToString());
            body = body.Replace("{20}", result.accuracy.ToString());
            body = body.Replace("{21}", result.total_short_trades.ToString());
            body = body.Replace("{22}", result.total_long_trades.ToString());
            body = body.Replace("{23}", result.total_profit_trades.ToString());
            body = body.Replace("{24}", result.total_loss_trades.ToString());
            body = body.Replace("{25}", result.total_short_trades_profitable.ToString());
            body = body.Replace("{26}", result.total_short_trades_loss.ToString());
            body = body.Replace("{27}", result.total_long_trades_profitable.ToString());
            body = body.Replace("{28}", result.total_long_trades_loss.ToString());
            body = body.Replace("{29}", result.maximum_consecutive_wins.ToString());
            body = body.Replace("{30}", result.maximum_consecutive_losses.ToString());
            body = body.Replace("{31}", result.maximum_consecutive_losses_factor.ToString());
            body = body.Replace("{33}", result.percentage_short_trades.ToString());
            body = body.Replace("{34}", result.percentage_long_trades.ToString());
            body = body.Replace("{35}", result.percentage_profit_trades.ToString());
            body = body.Replace("{36}", result.percentage_loss_trades.ToString());
            body = body.Replace("{37}", result.percentage_short_trades_profitable.ToString());
            body = body.Replace("{38}", result.percentage_short_trades_loss.ToString());
            body = body.Replace("{39}", result.percentage_long_trades_profitable.ToString());
            body = body.Replace("{40}", result.percentage_long_trades_loss.ToString());

            body = body.Replace("{50}", result.tradesize_max.ToString());
            body = body.Replace("{51}", result.tradesize_min.ToString());
            body = body.Replace("{52}", result.tradesize_mean.ToString());
            body = body.Replace("{53}", result.tradesize_median.ToString());
            body = body.Replace("{54}", result.tradesize_sd.ToString());

            body = body.Replace("{55}", result.tradeduration_max.ToString());
            body = body.Replace("{56}", result.tradeduration_min.ToString());
            body = body.Replace("{57}", result.tradeduration_mean.ToString());
            body = body.Replace("{58}", result.tradeduration_median.ToString());
            body = body.Replace("{59}", result.tradeduration_sd.ToString());
            body = body.Replace("{60}", result.total_SL_mismatch.ToString());
            body = body.Replace("{61}", result.total_TP_mismatch.ToString());
            body = body.Replace("{2}", result.total_reject_trades.ToString());

            body = body.Replace("{70}", result.pips_won.ToString());
            body = body.Replace("{71}", result.pips_won_min.ToString());
            body = body.Replace("{72}", result.pips_won_max.ToString());
            body = body.Replace("{73}", result.pips_won_avg.ToString());
            body = body.Replace("{74}", result.pips_loss.ToString());
            body = body.Replace("{75}", result.pips_loss_min.ToString());
            body = body.Replace("{76}", result.pips_loss_max.ToString());
            body = body.Replace("{77}", result.pips_loss_avg.ToString());


            if (string.IsNullOrEmpty(result.title))
            {
                body = body.Replace("{41}", string.Join(",", result.Basket));
            }
            else
            {
                body = body.Replace("{41}", result.title);
            }
            body = body.Replace("{42}", result.window.ToString());
            body = body.Replace("{43}", DateTime.Now.ToString());
            body = body.Replace("{44}", string.Format("window{0}, bandwidth={1}, transactioncost={2}, leverage={3}", result.window, result.bandwidth, result.transactionCost, result.leverage));

            webBrowser1.DocumentText = body;


            frmPlot plot = new frmPlot();

            plot.Show();
            plot.draw(result.balance_history.ToArray(), "Equity curve", "Time", "Equity");
        }
        public StrategyTesterResult[] Run()
        {
            StrategyTesterResult[] result = new StrategyTesterResult[40];
            #region Initialize Results
            for (int i = 0; i < 40; i++)
            {
                result[i] = new StrategyTesterResult();
                //result[i].Symbol1 = Symbol1;
                //result[i].Symbol2 = Symbol2;
                result[i].window          = period;
                result[i].bandwidth       = (i + 1) * 0.125;
                result[i].transactionCost = transactionCost;
                result[i].initialDeposit  = initialDeposit;
                result[i].leverage        = leverage;
            }
            #endregion
            #region Critial variables for trading system
            int[]    current_order     = new int[40];
            int[]    previous_position = new int[40];
            int[]    current_position  = new int[40];
            double[] openprice1        = new double[40];
            double[] openprice2        = new double[40];
            #endregion


            for (int i = period - 1; i < n_data; i++)
            {
                double sum  = 0;
                double sd   = 0;
                double mean = 0;


                for (int j = 0; j < period; j++)
                {
                    sum += Ratio[i - j];
                }
                mean = sum / period;
                sum  = 0;
                for (int j = 0; j < period; j++)
                {
                    sum += ((Ratio[i - j] - mean) * (Ratio[i - j] - mean));
                }
                sd = Math.Sqrt(sum / period);

                for (int j = 0; j < 40; j++)
                {
                    #region Main Loop
                    double deviation = (j + 1) * 0.125 * sd;
                    double upperBand = mean + deviation;
                    double lowerBand = mean - deviation;


                    if (Ratio[i] >= upperBand)
                    {
                        current_position[j] = 1;
                    }
                    else if (Ratio[i] < upperBand && Ratio[i] > mean)
                    {
                        current_position[j] = 2;
                    }
                    else if (Ratio[i] <= mean && Ratio[i] > lowerBand)
                    {
                        current_position[j] = 3;
                    }
                    else
                    {
                        current_position[j] = 4;
                    }


                    //######################### Close open trades #####################################################


                    if (current_position[j] >= 3 && current_order[j] == -1)
                    {
                        //Close sell order
                        #region close sell order

                        double pip1 = price_to_pip(openprice1[j], Pair1[i], 0);
                        double pip2 = price_to_pip(Pair2[i], openprice2[j], 1) * correlationDirection;

                        double pipcost1 = pipCostSeries[Symbol1CounterIndex, i];
                        double pipcost2 = pipCostSeries[Symbol2CounterIndex, i];


                        double netprofit = pip1 * pipcost1 + pip2 * pipcost2;
                        netprofit -= (transactionCost * pipcost1 + transactionCost * pipcost2);          //minus transaction cost from the profit. Note that there are two transactions

                        current_order[j] = 0;
                        #region resultupdate


                        result[j].total_trades++;
                        result[j].total_short_trades++;

                        if (netprofit < 0)
                        {
                            result[j].total_loss_trades++;

                            result[j].total_short_trades_loss++;
                        }
                        else
                        {
                            result[j].total_profit_trades++;

                            result[j].total_short_trades_profitable++;
                        }
                        #endregion
                        #endregion
                    }
                    else if (current_position[j] <= 2 && current_order[j] == 1)
                    {
                        //Close Buy order
                        #region close buy order

                        double pip1 = price_to_pip(Pair1[i], openprice1[j], 0);                        //Get profit of this buy order (first currency)
                        double pip2 = price_to_pip(openprice2[j], Pair2[i], 1) * correlationDirection; //in the case of positively correlated pair, the second currency is a sell..  For negatively correlated pair, it is a buy

                        double pipcost1 = pipCostSeries[Symbol1CounterIndex, i];
                        double pipcost2 = pipCostSeries[Symbol2CounterIndex, i];

                        double netprofit = pip1 * pipcost1 + pip2 * pipcost2;
                        netprofit -= (transactionCost * pipcost1 + transactionCost * pipcost2);          //minus transaction cost from the profit. Note that there are two transactions

                        current_order[j] = 0;
                        #region resultupdate

                        result[j].total_trades++;
                        result[j].total_long_trades++;

                        if (netprofit < 0)
                        {
                            result[j].total_loss_trades++;
                            result[j].total_long_trades_loss++;
                        }
                        else
                        {
                            result[j].total_profit_trades++;
                            result[j].total_long_trades_profitable++;
                        }
                        #endregion
                        #endregion
                    }
                    //################################## Open trade signals ######################################



                    if (previous_position[j] == 1 && current_position[j] == 2 && current_order[j] == 0)
                    {
                        //Sell order
                        #region Execute sell order
                        current_order[j] = -1;         //Sell corresponds to -1
                        openprice1[j]    = Pair1[i];
                        openprice2[j]    = Pair2[i];


                        #endregion
                    }
                    else if (previous_position[j] == 4 & current_position[j] == 3 && current_order[j] == 0)
                    {
                        //Buy order
                        #region Execute buy order
                        current_order[j] = 1;           //Buy corresponds to +1
                        openprice1[j]    = Pair1[i];
                        openprice2[j]    = Pair2[i];


                        #endregion
                    }
                    //#####################################################################################


                    previous_position[j] = current_position[j];
                    #endregion
                }
            }

            for (int i = 0; i < 40; i++)
            {
                result[i].postMortem();
            }
            return(result);
        }
Esempio n. 6
0
        private void cmdBackTest_Click(object sender, EventArgs e)
        {
            Dictionary <DateTime, int> M5Index = new Dictionary <DateTime, int>();

            Dictionary <string, DateTime[]> reff = new Dictionary <string, DateTime[]>();

            foreach (KeyValuePair <string, int> kvp in Global.Instance.TotalBars)
            {
                reff.Add(kvp.Key, new DateTime[kvp.Value]);
            }


            double transactionCost = 0;
            double leverage;
            double initialDeposit = 0;

            StringBuilder title = new StringBuilder();

            if (!double.TryParse(txtTransactionCost.Text, out transactionCost))
            {
                MessageBox.Show("Invalid transaction cost");
                return;
            }
            if (!double.TryParse(txtLeverage.Text, out leverage))
            {
                MessageBox.Show("Invalid leverage");
                return;
            }
            if (!double.TryParse(txtInitialDeposit.Text, out initialDeposit))
            {
                MessageBox.Show("Invalid initial deposit");
                return;
            }

            using (StreamReader reader = new StreamReader(Global.Instance.data_folder_path + "\\m5\\EURUSD.csv"))
            {
                string line = null;
                int    i    = 0;
                while ((line = reader.ReadLine()) != null)
                {
                    string[] ext = line.Split(',');
                    M5Index.Add(DateTime.Parse(ext[0]), i);
                    i++;
                }
                reader.Close();
            }

            M5Index.Add(new DateTime(2011, 12, 25, 22, 00, 00), 42311);
            M5Index.Add(new DateTime(2012, 1, 2, 2, 00, 00), 43733);

            M5Index.Add(new DateTime(2011, 2, 6, 17, 00, 00), 51265);
            M5Index.Add(new DateTime(2012, 1, 1, 22, 00, 00), 43732);

            foreach (KeyValuePair <string, int> kvp in Global.Instance.TotalBars)
            {
                if (kvp.Key == "m5")
                {
                    continue;
                }
                using (StreamReader reader = new StreamReader(Global.Instance.data_folder_path + "\\" + kvp.Key + "\\EURUSD.csv"))
                {
                    string line = null;
                    int    i    = 0;
                    while ((line = reader.ReadLine()) != null)
                    {
                        string[] ext = line.Split(',');
                        reff[kvp.Key][i] = DateTime.Parse(ext[0]);
                        i++;
                    }
                    reader.Close();
                }
            }
            ;

            string[] systems = txtSystems.Text.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            StrategyTesterResult[] results = new StrategyTesterResult[systems.Length];
            StrategyTesterResult   res     = new StrategyTesterResult();
            List <int>             Actions = new List <int>();


            for (int i = 0; i < systems.Length; i++)
            {
                #region main loop
                string[] ext;
                if (systems[i].Contains(','))
                {
                    ext = systems[i].Split(',');
                }
                else
                {
                    ext = systems[i].Split('\t');
                }
                string Symbol1   = ext[0];
                string Symbol2   = ext[1];
                int    period    = int.Parse(ext[2]);
                double bandwidth = double.Parse(ext[3]);
                string timeframe = ext[4];

                SingleRun singlerun = new SingleRun(new string[1], timeframe);
                singlerun.TransactionCost = transactionCost;
                singlerun.Bandwidth       = bandwidth;
                results[i] = singlerun.Run();


                res.total_trades                  += results[i].total_trades;
                res.total_short_trades            += results[i].total_short_trades;
                res.total_long_trades             += results[i].total_long_trades;
                res.total_short_trades_loss       += results[i].total_short_trades_loss;
                res.total_long_trades_loss        += results[i].total_long_trades_loss;
                res.total_short_trades_profitable += results[i].total_short_trades_profitable;
                res.total_long_trades_profitable  += results[i].total_long_trades_profitable;
                res.total_profit_trades           += results[i].total_profit_trades;
                res.total_loss_trades             += results[i].total_loss_trades;



                title.Append(Symbol1 + "-" + Symbol2);
                if (i < systems.Length - 1)
                {
                    title.Append("  &  ");
                }

                #endregion
            }

            Actions.Sort();
            List <int>    OpenOrders   = new List <int>();
            List <int>    CloseOrders  = new List <int>();
            List <double> Profit1      = new List <double>();
            List <double> Profit2      = new List <double>();
            List <double> Pipcost1     = new List <double>();
            List <double> Pipcost2     = new List <double>();
            List <int>    PositionSize = new List <int>();

            int[]  pos   = new int[results.Length];
            bool[] state = new bool[results.Length];

            int max_open_positions             = 0;
            int total_number_of_open_positions = 0;


            for (int i = 0; i < Actions.Count; i++)
            {
                for (int j = 0; j < results.Length; j++)
                {
                }
                int n_open_positions = open_positions(state);
                total_number_of_open_positions += n_open_positions;
                if (n_open_positions > max_open_positions)
                {
                    max_open_positions = n_open_positions;
                }
            }



            res.leverage = leverage;

            res.title          = title.ToString();
            res.initialDeposit = initialDeposit;

            res.transactionCost = transactionCost;

            try
            {
                res.percentage_short_trades = Math.Round((double)(res.total_short_trades * 100 / res.total_trades), 1);
            }
            catch { }
            try
            {
                res.percentage_long_trades = Math.Round((double)(res.total_long_trades * 100 / res.total_trades), 1);
            }
            catch { }
            try
            {
                res.percentage_short_trades_profitable = Math.Round((double)(res.total_short_trades_profitable * 100 / res.total_short_trades), 1);
            }
            catch { }
            try
            {
                res.percentage_short_trades_loss = Math.Round((double)(res.total_short_trades_loss * 100 / res.total_short_trades), 1);
            }
            catch { }
            try
            {
                res.percentage_long_trades_profitable = Math.Round((double)(res.total_long_trades_profitable * 100 / res.total_long_trades), 1);
            }
            catch { }
            try
            {
                res.percentage_long_trades_loss = Math.Round((double)(res.total_long_trades_loss * 100 / res.total_long_trades), 1);
            }
            catch { }



            if (res.total_trades > 0)
            {
                res.accuracy = Math.Round((double)(res.total_profit_trades * 100) / res.total_trades, 1);
            }

            res.maximum_open_positions = max_open_positions;
            frmResults frm = new frmResults(res);
            frm.Show();
        }
Esempio n. 7
0
        private void MegaOptimizationloadAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fb = new FolderBrowserDialog();

            fb.SelectedPath = Application.StartupPath;
            fb.Description  = "Please select result folder";

            if (fb.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            DirectoryInfo rootdir = new DirectoryInfo(fb.SelectedPath);


            SaveFileDialog sf = new SaveFileDialog();

            sf.Filter           = "CSV files (*.csv) | *.csv";
            sf.InitialDirectory = Application.StartupPath;

            if (sf.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            //List<string> InvalidBaskets = new List<string>();
            //using (StreamReader reader = new StreamReader("../../InvalidBaskets.txt"))
            //{
            //    string line = null;
            //    while ((line = reader.ReadLine()) != null)
            //    {
            //        InvalidBaskets.Add(line);
            //    }
            //    reader.Close();
            //}


            int count = 0;

            using (StreamWriter sw = new StreamWriter(sf.FileName))
            {
                #region main loop
                foreach (DirectoryInfo dir2 in rootdir.GetDirectories())
                {
                    foreach (DirectoryInfo dir3 in dir2.GetDirectories())
                    {
                        foreach (FileInfo file in dir3.GetFiles())
                        {
                            #region file looop
                            StrategyTesterResult[,] resultset;
                            BinaryFormatter bformatter = new BinaryFormatter();
                            using (FileStream stream = File.Open(file.FullName, FileMode.Open))
                            {
                                resultset = (StrategyTesterResult[, ])bformatter.Deserialize(stream);
                                stream.Close();
                            }
                            count += (resultset.GetLength(0) * resultset.GetLength(1));
                            for (int i = 0; i < resultset.GetLength(0); i++)
                            {
                                for (int j = 0; j < resultset.GetLength(1); j++)
                                {
                                    count++;
                                    StrategyTesterResult result = resultset[i, j];
                                    if (result.final_balance < 2000)
                                    {
                                        continue;
                                    }

                                    StringBuilder sb     = new StringBuilder();
                                    string        basket = string.Join(",", result.Basket);
                                    sb.Append("\"" + basket + "\""); sb.Append(",");
                                    sb.Append(i.ToString()); sb.Append(",");
                                    sb.Append(result.window.ToString()); sb.Append(",");
                                    sb.Append(result.bandwidth.ToString()); sb.Append(",");
                                    sb.Append(dir2.Name); sb.Append(",");
                                    sb.Append(result.final_balance.ToString()); sb.Append(",");
                                    sb.Append(result.total_trades.ToString()); sb.Append(",");
                                    sb.Append(result.accuracy.ToString()); sb.Append(",");
                                    sb.Append(result.estimate_monthly_profit.ToString()); sb.Append(",");
                                    sb.Append(result.pips_net.ToString()); sb.Append(",");
                                    sb.Append(result.pips_won_max.ToString()); sb.Append(",");
                                    sb.Append(result.pips_won_min.ToString()); sb.Append(",");
                                    sb.Append(result.pips_won_avg.ToString()); sb.Append(",");
                                    sb.Append(result.pips_loss_max.ToString()); sb.Append(",");
                                    sb.Append(result.pips_loss_min.ToString()); sb.Append(",");
                                    sb.Append(result.pips_loss_avg.ToString()); sb.Append(",");
                                    sb.Append(result.maximum_consecutive_wins.ToString()); sb.Append(",");
                                    sb.Append(result.maximum_consecutive_losses.ToString()); sb.Append(",");
                                    sw.WriteLine(sb.ToString());
                                }
                            }
                            sw.Flush();
                            #endregion
                        }
                    }
                }
                #endregion
                sw.Close();
            }
            MessageBox.Show("Done " + count.ToString());
        }
Esempio n. 8
0
        private void SingleRunrunToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int    window, leverage, responseVariableIndex, maxOpenPositions;
            double bandwidth, transactionCost, initialDeposit;

            string[] basket;

            if (!int.TryParse(txtWindow.Text, out window))
            {
                MessageBox.Show("Invalid window");
                return;
            }
            if (!int.TryParse(txtLeverage.Text, out leverage))
            {
                MessageBox.Show("Invalid leverage");
                return;
            }
            if (!int.TryParse(txtMaxOpenPositions.Text, out maxOpenPositions))
            {
                MessageBox.Show("Invalid max open positions");
                return;
            }
            if (!double.TryParse(txtBandwidth.Text, out bandwidth))
            {
                MessageBox.Show("Invalid bandwidth");
                return;
            }
            if (!double.TryParse(txtTransactionCost.Text, out transactionCost))
            {
                MessageBox.Show("Invalid transaction cost");
                return;
            }
            if (!double.TryParse(txtInitialDeposit.Text, out initialDeposit))
            {
                MessageBox.Show("Invalid initial deposit");
                return;
            }
            basket = txtBasket.Text.Split(',');
            responseVariableIndex = cboResponseV.SelectedIndex;
            if (basket.Length <= 1)
            {
                MessageBox.Show("Basket must contain a minimum of two symbols separated by comma");
                return;
            }
            if (responseVariableIndex < 0 || responseVariableIndex >= basket.Length)
            {
                MessageBox.Show("Response variable index must be greater than 0 and less than the total number of symbols in the basket");
                return;
            }
            SingleRun test = new SingleRun(basket, cboTimeFrame.Text);

            test.Leverage              = leverage;
            test.InitialDeposit        = initialDeposit;
            test.Bandwidth             = bandwidth;
            test.TransactionCost       = transactionCost;
            test.Responsevariableindex = responseVariableIndex;
            test.Window           = window;
            test.MaxOpenPositions = maxOpenPositions;
            StrategyTesterResult res = test.Run();

            frmResults frm = new frmResults(res);

            frm.Show();
        }