Пример #1
0
 public LiveTradeEngine()
 {
     _session = new FXSession();
     _opEngine = new OrderPlacementEngine(_session);
     _priceEngine = new HistoricPriceEngine(_session);
     _accountManager = new LiveAccountManager(_opEngine);
 }
Пример #2
0
 public HistoricPriceEngine(FXSession session)
 {
     _mktData = new Quantum();
     _completeCounter = 0;
     complete = false;
     mHandler = HistoricDataReceived;
     this.session = session;
 }
Пример #3
0
 public void RunJob(FXSession fxsession)
 {
     foreach (string symbol in symbols)
     {
         //ResponseHandler.GetHistoricPrices(fxsession, symbol, timeframe, numTicks);
         Thread.Sleep(100); // don't overload api
     }
 }
Пример #4
0
 public void LoadData()
 {
     FXSession session = new FXSession();
     session.InitializeSession();
     
     foreach (string s in sList)
     {
         HistoricPriceEngine h = new HistoricPriceEngine(session);
         h.GetLongHistoricPrices(symbol, s, ticks);
         while(!h.Complete) Thread.Sleep(100);   
         mData.Add(h.Data);
     }
 }
Пример #5
0
        public static Quantum QuantumFromLiveData(string symbol, string timeframe, int ticks)
        {
            FXSession session = new FXSession();

            session.InitializeSession();
            HistoricPriceEngine h = new HistoricPriceEngine(session);

            h.GetLongHistoricPrices(symbol, timeframe, ticks);
            while (!h.Complete)
            {
                Thread.Sleep(100);
            }

            return(h.Data);
        }
Пример #6
0
        public void LoadData()
        {
            FXSession session = new FXSession();

            session.InitializeSession();

            foreach (string s in sList)
            {
                HistoricPriceEngine h = new HistoricPriceEngine(session);
                h.GetLongHistoricPrices(symbol, s, ticks);
                while (!h.Complete)
                {
                    Thread.Sleep(100);
                }
                mData.Add(h.Data);
            }
        }
Пример #7
0
        public void LoadDataLive(string symbol, string timeframe, int ticks)
        {
            var session  = new FXSession();
            session.InitializeSession();
            while (!session.LoggedIn)
            {
                Thread.Sleep(100);
            }
            var price = new HistoricPriceEngine(session);
            price.GetLongHistoricPrices(symbol, timeframe, ticks);

            while (!price.Complete)
            {
                Thread.Sleep(100);
            }

            _dataSet.Add(price.Data);

            session.EndSession();
        }
Пример #8
0
        public static MarketDataEventArg ProcessMarketData(FXSession connection, O2GResponse response)
        {
            try
            {
                O2GResponseReaderFactory rrfactory = connection.Session.getResponseReaderFactory();
                O2GMarketDataSnapshotResponseReader mReader = rrfactory.createMarketDataSnapshotReader(response);

                var d = new SortedList<DateTime, Tick>(mReader.Count);

                for (int i = 0; i < mReader.Count; i++)
                {
                    // information like reader.getDate(i), reader.getBidOpen(i), reader.getBidHigh(i), reader.getBidLow(i), reader.getBidClose(i), reader.getVolume(i) is now available
                    //Console.WriteLine(i + ":" + mReader.getDate(i).ToString() + ":" + mReader.getBidOpen(i));
                    //create a quantum of ticks for the market data
                    var tick = new Tick(
                        mReader.getBid(i),
                        mReader.getBidOpen(i),
                        mReader.getBidHigh(i),
                        mReader.getBidLow(i),
                        mReader.getBidClose(i),
                        mReader.getAsk(i),
                        mReader.getAskOpen(i),
                        mReader.getAskHigh(i),
                        mReader.getAskLow(i),
                        mReader.getAskClose(i),
                        mReader.getVolume(i),
                        mReader.getDate(i));
                        
                    d.Add(mReader.getDate(i), tick);
                }

                var q = new Quantum(d);
                return new MarketDataEventArg(q);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return new MarketDataEventArg(new Quantum(new SortedList<DateTime, Tick>(300)));
            }
        }
Пример #9
0
        public static MarketDataEventArg ProcessMarketData(FXSession connection, O2GResponse response)
        {
            try
            {
                O2GResponseReaderFactory            rrfactory = connection.Session.getResponseReaderFactory();
                O2GMarketDataSnapshotResponseReader mReader   = rrfactory.createMarketDataSnapshotReader(response);

                var d = new SortedList <DateTime, Tick>(mReader.Count);

                for (int i = 0; i < mReader.Count; i++)
                {
                    // information like reader.getDate(i), reader.getBidOpen(i), reader.getBidHigh(i), reader.getBidLow(i), reader.getBidClose(i), reader.getVolume(i) is now available
                    //Console.WriteLine(i + ":" + mReader.getDate(i).ToString() + ":" + mReader.getBidOpen(i));
                    //create a quantum of ticks for the market data
                    var tick = new Tick(
                        mReader.getBid(i),
                        mReader.getBidOpen(i),
                        mReader.getBidHigh(i),
                        mReader.getBidLow(i),
                        mReader.getBidClose(i),
                        mReader.getAsk(i),
                        mReader.getAskOpen(i),
                        mReader.getAskHigh(i),
                        mReader.getAskLow(i),
                        mReader.getAskClose(i),
                        mReader.getVolume(i),
                        mReader.getDate(i));

                    d.Add(mReader.getDate(i), tick);
                }

                var q = new Quantum(d);
                return(new MarketDataEventArg(q));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(new MarketDataEventArg(new Quantum(new SortedList <DateTime, Tick>(300))));
            }
        }
Пример #10
0
        public void LoadDataLive(string symbol, string timeframe, int ticks)
        {
            var session = new FXSession();

            session.InitializeSession();
            while (!session.LoggedIn)
            {
                Thread.Sleep(100);
            }
            var price = new HistoricPriceEngine(session);

            price.GetLongHistoricPrices(symbol, timeframe, ticks);

            while (!price.Complete)
            {
                Thread.Sleep(100);
            }

            _dataSet.Add(price.Data);

            session.EndSession();
        }
Пример #11
0
        public static void Process(FXSession session, string symbol1, string symbol2, string timeframe, int length)
        {


            HistoricPriceEngine h1 = new HistoricPriceEngine(session);
            h1.GetLongHistoricPrices(symbol1, timeframe, length);

            while (!h1.Complete)
            {
                Thread.Sleep(100);
            }

            HistoricPriceEngine h2 = new HistoricPriceEngine(session);
            h2.GetLongHistoricPrices(symbol2, timeframe, length);

            while (!h2.Complete)
            {
                Thread.Sleep(100);
            }
            //-----------------------

            var dateTimeList = new SortedList<DateTime, int>();

            Quantum q1 = h1.Data;
            Quantum q2 = h2.Data;


            var priceData = new DenseMatrix(2, q1.Data.Count);

            for (int j = 0; j < ((q1.Data.Count <= q2.Data.Count)?q1.Data.Count:q2.Data.Count); j++ )
            {
                dateTimeList.Add(q1.Data.Values[j].Time, 1);
                priceData[0, j] = q1.Data.Values[j].BidClose;
                priceData[1, j] = q2.Data.Values[j].BidClose;
            }

            Vector<double> price1 = priceData.Row(0);
            Vector<double> price2 = priceData.Row(1);
            //Statistics.ApplyFunction((DenseVector)price1, Math.Log);
            //Statistics.ApplyFunction((DenseVector)price2, Math.Log);

            DenseVector norm1 = price1.ToArray().NormalizeZScore();
            DenseVector norm2 = price2.ToArray().NormalizeZScore();

            var newsym = new string[] {symbol1, symbol2, "spread"};

            var m = new DenseMatrix(6, norm1.Count);
            m.SetRow(0, norm1);
            m.SetRow(1, norm2);
            m.SetRow(2, (norm1 - norm2).ToArray().NormalizeZScore());

            string filename = symbol1.Replace('/', '_') + "-" + symbol2.Replace('/', '_') + ".html";


            Visualize.GenerateMultiPaneGraph(newsym, dateTimeList.Keys.ToArray(), m, QSConstants.DEFAULT_DATA_FILEPATH + filename,
                new ChartOption[]{new ChartOption(), new ChartOption(){Layover = true, YPosition = 0}, new ChartOption(){YPosition = 1} }, null, filename + ".json");

            FileUpload.UploadFileToFTP(QSConstants.DEFAULT_DATA_FILEPATH + filename, filename);
            FileUpload.UploadFileToFTP(QSConstants.DEFAULT_DATA_FILEPATH + filename + ".json", filename + ".json");

            double Spread = m[2, m.ColumnCount - 1];

            if (Spread > 2.0 && m[2, m.ColumnCount - 2] <= 2.0)
                Emailer.SendEmail(symbol1 + "-" + symbol2 + " Spread Above 2.0", "Test");

            if (Spread < -2.0 && m[2, m.ColumnCount - 2] >= -2.0)
                Emailer.SendEmail(symbol1 + "-" + symbol2 + " Spread Below -2.0", "Test");

        }
Пример #12
0
 public AccountInformation(FXSession session)
 {
     this.session = session;
     mHandler = AccountInformationReceived;
     session.AttachHandler(mHandler);
 }
Пример #13
0
 public static AccountInformationEventArg ProcessData(FXSession connection, O2GResponse response)
 {
     return new AccountInformationEventArg();
 }
Пример #14
0
 public OrderPlacementEngine(FXSession session)
 {
     _session = session;
 }
Пример #15
0
        private static void Main()
        {
            //TestLiveCointegration.Run();

            /*
             * IndicatorMatrix im = new IndicatorMatrix("EUR/USD");
             * im.LoadData();
             * im.Execute();
             */

            //TestIndicator.TestMA(QSConstants.DEFAULT_DATA_FILEPATH + "GBPUSD15M.xml", 14000, new QSPolyMA(40), new ZLEMA(40));
            //TestIndicator.TestChannelLive(new QSPolyChannel(), "EUR/USD", "m5", 5000 );
            //TestIndicator.TestChannel(new KirshenbaumBands(20), QSConstants.DEFAULT_DATA_FILEPATH + "EURUSD15M.xml", 10000);
            //TestIndicator.TestMA(QSConstants.DEFAULT_DATA_FILEPATH + "EURUSD1H.xml", 15000,  new SMA(25), new DWT(25, 5));
            //TestIndicator.TestGraph(new ReversalGenesis(50),  QSConstants.DEFAULT_DATA_FILEPATH + "AUDUSD1H.xml", 15000);
            //TestIndicator.TestGraph(new HurstIndicator(256), QSConstants.DEFAULT_DATA_FILEPATH + "AUDUSD1H.xml", 15000);
            //TestIndicator.TestGraphLive(new Genesis(30), "m30", "EUR/USD", 10000);
            //TestIndicator.TestGraphLive(new PercentileRank(250, new SMA(200)), "H1", "EUR/USD", 1000);
            //TestIndicator.TestGraphLive(new PercentileRank(250, new SMA(200,new HistoricalVol(50))), "H1", "EUR/USD", 100000);
            //TestIndicator.TestGraphLive(new WilliamsR(), "H1", "EUR/USD", 100000);
            //TestIndicator.TestGraph(new PercentileRank(252, new SMA(251)), QSConstants.DEFAULT_DATA_FILEPATH + "EURUSD1H.xml", 10000);
            Quantum        q1 = Quantum.ExcelToQuantum(QSConstants.DEFAULT_DATA_FILEPATH + "EURUSD1H.xml", "EUR/USD");
            Quantum        q2 = Quantum.ExcelToQuantum(QSConstants.DEFAULT_DATA_FILEPATH + "GBPUSD1H.xml", "GBP/USD");
            Quantum        q3 = Quantum.ExcelToQuantum(QSConstants.DEFAULT_DATA_FILEPATH + "AUDUSD1H.xml", "AUD/USD");
            List <Quantum> lq = new List <Quantum>();

            lq.Add(q1);
            lq.Add(q2);
            lq.Add(q3);
            MultiQuantum        mq   = MultiQuantum.OrganizeMultiQuantum(lq);
            List <List <Tick> > list = mq.RevertToList();

            double[] dat1 = list[0].ToArray().Select(x => x.BidClose).ToArray().NormalizeZScore();
            double[] dat2 = list[1].ToArray().Select(x => x.BidClose).ToArray().NormalizeZScore();
            double[] dat3 = list[2].ToArray().Select(x => x.BidClose).ToArray().NormalizeZScore();

            DenseVector d11 = new DenseVector(dat1);
            DenseVector d12 = new DenseVector(dat2);
            DenseVector d13 = new DenseVector(dat3);

            DenseVector fe = ((.48 * d11) + (-0.22 * d12) + (-.46 * d13));

            Visualize.GenerateSimpleGraph(fe, "result.html");


            Console.Read();

            Func <Chromosome, double> fitnessFunc = new Func <Chromosome, double>(
                chromosome =>
            {
                double weight1 = ((RealCodedGene)chromosome[0]).GeneValue;
                double weight2 = ((RealCodedGene)chromosome[1]).GeneValue;
                double weight3 = ((RealCodedGene)chromosome[2]).GeneValue;

                double w1mod = weight1 / (weight1 + weight2 + weight3);
                double w2mod = weight2 / (weight1 + weight2 + weight3);
                double w3mod = weight3 / (weight1 + weight2 + weight3);

                DenseVector d1 = new DenseVector(dat1);
                DenseVector d2 = new DenseVector(dat2);
                DenseVector d3 = new DenseVector(dat3);

                double stdev = ((w1mod * d1) + (w2mod * d2) + (w3mod * d3)).StandardDeviation();

                return((stdev > 0) ? (1 / stdev) : 0.000001);
            }
                );

            Random r  = new Random();
            Gene   g1 = new RealCodedGene(0, r, new GeneConstraint((x => (double)x <1.0 && (double)x> -1.0))
            {
                HI = 1.0, LOW = -1.0
            });
            Gene g2 = new RealCodedGene(0, r, new GeneConstraint((x => (double)x <1.0 && (double)x> -1.0))
            {
                HI = 1.0, LOW = -1.0
            });
            Gene g3 = new RealCodedGene(0, r, new GeneConstraint((x => (double)x <1.0 && (double)x> -1.0))
            {
                HI = 1.0, LOW = -1.0
            });
            List <Gene> cfootprint = new List <Gene>();

            cfootprint.Add(g1);
            cfootprint.Add(g2);
            cfootprint.Add(g3);

            GeneticAlgorithm ga = new GeneticAlgorithm(
                fitnessFunc, cfootprint, 30, 200, 10
                );

            ga.Run();

            Console.Read();


            var ba1 = new BacktestEngine(0, 3010, true);

            ba1.LoadData(QSConstants.DEFAULT_DATA_FILEPATH + "EURUSD1H.xml", "EUR/USD");
            ba1.LoadData(QSConstants.DEFAULT_DATA_FILEPATH + "GBPUSD1H.xml", "GBP/USD");
            //ba.LoadDataLive("EUR/USD", "m5", 200000);
            //ba.LoadDataLive("GBP/USD", "m5", 20000);
            ba1.OrganizeData();
            ba1.LoadStrategy(new Cointegration());
            ba1.Execute();



            Console.Read();


            object[,] denseMatrix;
            ExcelUtil.Open(QSConstants.DEFAULT_DATA_FILEPATH + @"GBPUSD1H.xml", out denseMatrix);

            var mData = new List <double>();

            var predictor = new AC(60);

            for (int i = denseMatrix.GetLength(0); i > 1; i--)
            {
                DateTime dateTime = (DateTime)denseMatrix[i, 1];
                var      t        = new Tick(
                    0,
                    (double)denseMatrix[i, 6],
                    (double)denseMatrix[i, 7],
                    (double)denseMatrix[i, 8],
                    (double)denseMatrix[i, 9],
                    0,
                    (double)denseMatrix[i, 2],
                    (double)denseMatrix[i, 3],
                    (double)denseMatrix[i, 4],
                    (double)denseMatrix[i, 5],
                    (double)denseMatrix[i, 10],
                    dateTime
                    );

                double d = predictor.HandleNextTick(t);
                if (!d.Equals(double.NaN))
                {
                    mData.Add(d);
                }
            }

            int windowSize     = 5;
            int iterations     = 10000;
            int trainLength    = 5000;
            int validateLength = 1000;

            double[] trainData    = mData.ToArray().Take(trainLength).ToArray();
            double[] validateData = mData.ToArray().Skip(trainLength).ToArray().Take(validateLength).ToArray();

            Stage1NeuralNetwork nn = new Stage1NeuralNetwork(windowSize, iterations, trainData, validateData);

            nn.Execute(1);

            NeuralNetworkStrategy nns = new NeuralNetworkStrategy(windowSize)
            {
                NeuralNetwork = nn
            };

            var ba = new BacktestEngine(5000, 9200, true);

            //ba.LoadData(QSConstants.DEFAULT_DATA_FILEPATH + "GBPUSD15M.xml", "EUR/USD");
            ba.LoadData(QSConstants.DEFAULT_DATA_FILEPATH + "NZDUSD1H.xml", "GBP/USD");
            //ba.LoadDataLive("EUR/USD", "m5", 200000);
            //ba.LoadDataLive("GBP/USD", "m5", 20000);
            ba.OrganizeData();
            ba.LoadStrategy(nns);
            ba.Execute();


            Console.Read();

            /*
             * Func<Chromosome, double> function = (chromosome =>
             * {
             *  double fitness = 0.001;
             *
             *  ba.ResetAccount();
             *  ba.ResetStrategies();
             *  ba.LoadStrategy(new CustomStrategy(
             *         (int)(double)chromosome[0].GeneValue,
             *         (int)(double)chromosome[1].GeneValue,
             *         (int)(double)chromosome[2].GeneValue,
             *         (int)(double)chromosome[3].GeneValue,
             *         (int)(double)chromosome[4].GeneValue,
             *         (int)(double)chromosome[5].GeneValue,
             *         (int)(double)chromosome[6].GeneValue,
             *         (int)(double)chromosome[7].GeneValue,
             *         (int)(double)chromosome[8].GeneValue
             *      ));
             *  ba.Execute();
             *
             *
             *  fitness += ba.ret;
             *
             *  return (fitness > 0) ? fitness : 0.001;
             * }
             *  );
             *
             * var GA = new GeneticAlgorithm(function,
             *  new List<Gene>
             *  {
             *      new Gene(50, new Gene.Constraint(5,200)),
             *      new Gene(50, new Gene.Constraint(5,200)),
             *      new Gene(50, new Gene.Constraint(5,200)),
             *      new Gene(50, new Gene.Constraint(5,500)),
             *      new Gene(50, new Gene.Constraint(1,100)),
             *      new Gene(50, new Gene.Constraint(1,100)),
             *      new Gene(50, new Gene.Constraint(5,500)),
             *      new Gene(50, new Gene.Constraint(5,500)),
             *      new Gene(50, new Gene.Constraint(1,100))
             *  }) { Generations = 1000, Trials = 10 }
             *  ;
             *
             * GA.InitializePopulation();
             * GA.Run();
             *
             * Console.Read();
             */



            /*
             * object[,] denseMatrix;
             * ExcelUtil.Open(Constants.DEFAULT_DATA_FILEPATH + @"EURUSD1H.xml", out denseMatrix);
             *
             * var mData = new List<double>();
             *
             * var predictor = new RSI(40);
             *
             * for (int i = denseMatrix.GetLength(0); i > 1; i--)
             * {
             *  DateTime dateTime = (DateTime) denseMatrix[i, 1];
             *  var t = new Tick(
             *          0,
             *          (double) denseMatrix[i, 6],
             *          (double) denseMatrix[i, 7],
             *          (double) denseMatrix[i, 8],
             *          (double) denseMatrix[i, 9],
             *          0,
             *          (double) denseMatrix[i, 2],
             *          (double) denseMatrix[i, 3],
             *          (double) denseMatrix[i, 4],
             *          (double) denseMatrix[i, 5],
             *          (double) denseMatrix[i, 10],
             *          dateTime
             *          );
             *
             *  double d = predictor.HandleNextTick(t);
             *  if (!d.Equals(double.NaN))
             *      mData.Add(d);
             * }
             *
             * int windowSize = 5;
             * int iterations = 5000;
             * int trainLength = 5000;
             * int validateLength = 1000;
             * double[] trainData = mData.ToArray().Take(trainLength).ToArray();
             * double[] validateData = mData.ToArray().Skip(trainLength).ToArray().Take(validateLength).ToArray();
             *
             * Stage1NeuralNetwork nn = new Stage1NeuralNetwork(windowSize, iterations, trainData, validateData);
             * nn.Execute(1);
             *
             * NeuralNetworkStrategy nns = new NeuralNetworkStrategy(windowSize){NeuralNetwork = nn};
             */

            /*
             * bool seao = true;
             * if (seao)
             * {
             *
             *  var ba = new BacktestEngine(0, 50000, true);
             *  ba.LoadDataLive("EUR/USD", "m30", 80000);
             *
             *  //ba.LoadStrategy(nns);
             *  ba.LoadStrategy(new RSIEntry(50){LongEntry = 60, ShortEntry = 40});
             *  ba.LoadStrategy(new RSIExit(50){ LongExit = 70, ShortExit = 30 });
             *
             *  //ba.LoadStrategy(new Pyramid(.1, .05, .001));
             *  ba.Execute();
             *
             *  Console.Read();
             * }
             *
             * BacktestEngine[] barray = new BacktestEngine[2];
             *
             * Func<Chromosome, double> function = (chromosome =>
             * {
             *  double fitness = 0.001;
             *  foreach (BacktestEngine bx in barray)
             *  {
             *      bx.ResetAccount();
             *      bx.ResetStrategies();
             *      bx.LoadStrategy(new CustomStrategy());
             *      bx.LoadStrategy(new Pyramid((double) chromosome[0].GeneValue,
             *          (double) chromosome[1].GeneValue,
             *          (double) chromosome[2].GeneValue));
             *      bx.Execute();
             *
             *      if (bx.ret > 100)
             *          fitness += 100;
             *      else
             *          fitness += bx.ret;
             *  }
             *
             *  return (fitness > 0) ? fitness/5 : 0.001;
             * }
             *  );
             *
             * var GA = new GeneticAlgorithm(function,
             *  new List<Gene>
             *  {
             *      new Gene(5, new Gene.Constraint(0,1.0)),
             *      new Gene(5, new Gene.Constraint(0,1.0)),
             *      new Gene(5, new Gene.Constraint(0,1.0/100.0))
             *  }) {Generations = 1000, Trials = 1}
             *  ;
             *
             * GA.InitializePopulation();
             * GA.Run();
             *
             * Console.Read();
             *
             * /*
             * b.Output = true;
             * b.ResetAccount();
             * b.ResetStrategies();
             * b.LoadStrategy(new RSIEntry()
             * {
             *  EntryTarget1 = (double)GA.maxC[0].GeneValue,
             *  EntryTarget2 = (double)GA.maxC[1].GeneValue
             * });
             * b.LoadStrategy(new RSIExit()
             * {
             *  ExitTarget1 = (double)GA.maxC[2].GeneValue,
             *  ExitTarget2 = (double)GA.maxC[3].GeneValue
             * });
             *
             *
             * b.Execute();
             */
            //Console.Read();


            //object[,] data;

            /*
             * ExcelUtil.Open("C:\\Users\\EL65628\\Work\\QuantSys\\data\\UCUM.xls", out data);
             * DenseMatrix d = ExcelUtil.ToMatrix(data, 2, 1283, 1, 2, true);
             *
             * DenseVector normchf = Statistics.NormalizeZScore(d.Column(0).ToArray());
             * DenseVector normmxn = Statistics.NormalizeZScore(d.Column(1).ToArray());
             *
             * DenseVector kurtmxn = new DenseVector(Statistics.AggregateWindow(d.Column(1).ToArray(),
             *  Statistics.Kurtosis, 50, false, false));
             *
             * DenseVector corre = new DenseVector((Statistics.AggregateWindow(
             *  Statistics.RawRateOfReturn(d.Column(0).ToArray()),
             *  Statistics.RawRateOfReturn(d.Column(1).ToArray()),
             *  Statistics.Correlation,
             *  80, false, true)));
             *
             * //DenseMatrix dNew = new DenseMatrix(3, 1282);
             * //dNew.SetRow(0, (DenseVector)d.Column(0).Normalize(100));
             * //dNew.SetRow(1, (DenseVector)d.Column(1).Normalize(100));
             * //dNew.SetRow(2, corre);
             *
             * Visualize.GenerateGraph(corre, "C:\\Users\\EL65628\\Work\\QuantSys\\data\\correlation.html");
             * Visualize.GenerateGraph(kurtmxn, "C:\\Users\\EL65628\\Work\\QuantSys\\data\\kurtosis.html");
             * //Visualize.GenerateGraph(normmxn, "C:\\Users\\EL65628\\Work\\QuantSys\\data\\diff2.html");
             * Visualize.GenerateGraph((DenseVector)(Statistics.NormalizeZScore((-1.5 * normmxn + .9 * normchf).ToArray())), "C:\\Users\\EL65628\\Work\\QuantSys\\data\\diff3.html");
             *
             * string[] symbols = { "usd/chf", "usd/mxn" ,"correlation"};
             * //Visualize.GenerateMultiSymbolGraph(symbols, dNew, new DateTime(), new TimeSpan(1, 0, 0), "C:\\Users\\EL65628\\Work\\QuantSys\\data\\diff.html");
             *
             *
             * int[] vectors = { 5, 3, 2, 4, 6, 7, 8, 9, 10, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54 };
             *
             * string vecstring = "1 0 0 0 1 0 1 1 0 0 0 0 1 0 1 0 1 1 1 1 1 0 1 1 1 0 0 0 1 1 1 0 0 0 1 0 0 0 0 1 1 1 1 0 0 0 1 1 0";
             *
             *
             * string[] vectemp = vecstring.Split(' ');
             * List<int> vec = new List<int>();
             *
             * for (int i = 0; i < vectors.Length; i++)
             * {
             *  if (vectemp[i]=="1") vec.Add(vectors[i]);
             * }
             *
             * //int[] vect = {13, 19, 25, 27 };
             * int[] vect = { 17, 18, 22, 27, 40, 49};
             *
             * ExcelUtil.Open("C:\\Users\\EL65628\\Work\\QuantSys\\data\\EURUSD1D.xml", out data);
             * TwoStageNN twoStageNn = new TwoStageNN(50, 200, data, vect);
             * twoStageNn.Execute();
             *
             *
             * //GeneticAlgorithm g = new GeneticAlgorithm();
             * //g.Run();
             *
             * Console.ReadLine();
             *
             * PortfolioOptimizer.Run();
             */

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            string[] currencies =
            {
                "EUR/USD",
                "GBP/USD",
                "USD/CAD",
                "USD/CHF",
                "AUD/USD",
                "NZD/USD",
                "USD/JPY",
                "USD/MXN",
                "USD/ZAR",
                "USD/PLN",
                "USD/TRY",
                "USD/DKK",
                "USD/SEK",
                "USD/NOK"
            };

            var currencypairs = new List <string[]>();


            for (int i = 0; i < currencies.Length; i++)
            {
                for (int j = 0; j < i; j++)
                {
                    if (currencies[i] != currencies[j])
                    {
                        string[] temp = { currencies[i], currencies[j] };
                        currencypairs.Add(temp);
                        Console.WriteLine(currencies[i] + " " + currencies[j]);
                    }
                }
            }


            /////////////////////////////////////////////////////////

            /*
             * FXSession fxsession1 = new FXSession();
             *
             * string[] tempgroup = { "AUD/USD", "NZD/USD" };
             *
             * Thread oThread1 = new Thread(new ThreadStart(fxsession1.InitializeSession));
             * oThread1.Start();
             *
             * while (fxsession1.LoginStatus.Equals(FXSession.LOGIN_STATUS.NOT_LOGGED_IN))
             * {
             *  Thread.Sleep(1000);
             *  Console.Write(".");
             * }
             *
             * if (fxsession1.LoginStatus.Equals(FXSession.LOGIN_STATUS.LOGGED_IN))
             * {
             *  //Job_SymbolSet job = new Job_SymbolSet(ex, "H1", 150, new EMA(14));
             *  //Job_CorrelationMatrix job = new Job_CorrelationMatrix(currencies, "D1", 300, Job_CorrelationMatrix.CovarianceType.RawReturn);
             *
             *  Job_Cointegration job = new Job_Cointegration(tempgroup, "m30", 300);
             *      fxsession1.PlaceJob(job);
             *      job.RunJob(fxsession1);
             *      Thread.Sleep(1000);
             * }
             *
             * Console.ReadLine();
             *
             */
            //////////////////////////////////////////////////////////////////

            while (true)
            {
                try
                {
                    var fxsession = new FXSession();


                    var oThread = new Thread(fxsession.InitializeSession);
                    oThread.Start();

                    while (!fxsession.LoggedIn)
                    {
                        Thread.Sleep(1000);
                        Console.Write(".");
                    }

                    if (fxsession.LoggedIn)
                    {
                        //Job_SymbolSet job = new Job_SymbolSet(ex, "H1", 150, new EMA(14));
                        //Job_CorrelationMatrix job = new Job_CorrelationMatrix(currencies, "D1", 300, Job_CorrelationMatrix.CovarianceType.RawReturn);

                        //Job_Cointegration.Process(fxsession, "USD/DKK", "USD/CHF", "m30", 3000);
                        //Console.Read();

                        foreach (var group in currencypairs)
                        {
                            if ((!group[0].Substring(0, 3).Equals("USD") && !group[1].Substring(0, 3).Equals("USD")) ||
                                (group[0].Substring(0, 3).Equals("USD") && group[1].Substring(0, 3).Equals("USD")))
                            {
                                try
                                {
                                    Job_Cointegration.Process(fxsession, group[0], group[1], "m30", 3000);
                                    Thread.Sleep(1000);
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e.Message);
                                }
                            }
                        }
                    }

                    fxsession.EndSession();
                    oThread.Abort();
                }

                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                Console.WriteLine(DateTime.Now.ToString());

                Thread.Sleep(1000 * 60 * 30);
            }

            Console.ReadLine();
        }
Пример #16
0
        public static void TestGraphLive(this AbstractIndicator ind, string timeframe, string symbol, int length)
        {
            //------------grab data
            FXSession session = new FXSession();
            session.InitializeSession();

            HistoricPriceEngine h = new HistoricPriceEngine(session);
            h.GetLongHistoricPrices(symbol, timeframe, length);

            while (!h.Complete)
            {
                Thread.Sleep(100);
            }
            //-----------------------

            Quantum q = h.Data;
            var dz = new DenseMatrix(4 + 1 + ind.SubIndicatorSize, q.Data.Count);
            List<string> names = new List<string>();
            names.Add("symbol");
            names.Add(ind.ToString());
            foreach (var indicator in ind.SubIndicators) names.Add(indicator.Key);

            //chartoptions
            ChartOption[] chartOptions = new ChartOption[names.Count];
            chartOptions[0] = new ChartOption() { Height = 400, YPosition = 0 };
            chartOptions[1] = new ChartOption() { Height = 200, YPosition = 1 };
            for (int i = 2; i < chartOptions.Length; i++)
                chartOptions[i] = new ChartOption() { Height = 0, YPosition = 1, Layover = true };

            int counter = 0;
            foreach (Tick tick in q)
            {
                dz[0, counter] = tick.BidOpen;
                dz[1, counter] = tick.BidHigh;
                dz[2, counter] = tick.BidLow;
                dz[3, counter] = tick.BidClose;

                dz[4, counter] = ind.HandleNextTick(tick);

                int icounter = 5;
                foreach (var subind in ind.SubIndicators.Values)
                {
                    dz[icounter, counter] = subind[0];
                    icounter++;
                }

                counter++;
            }


            Visualize.GenerateMultiPaneGraph(names.ToArray(), q.Data.Keys.ToArray(), dz, QSConstants.DEFAULT_DATA_FILEPATH + @"results.html",
                chartOptions);

            Console.WriteLine("Done Generating Graph for " + ind.ToString());
        }
Пример #17
0
 public OrderPlacementEngine(FXSession session)
 {
     _session = session;
 }
Пример #18
0
 public AccountInformation(FXSession session)
 {
     this.session = session;
     mHandler     = AccountInformationReceived;
     session.AttachHandler(mHandler);
 }
Пример #19
0
 public SessionStatusListener(FXSession connection)
 {
     _connection = connection;
 }
Пример #20
0
        public static void Process(FXSession session, string symbol1, string symbol2, string timeframe, int length)
        {
            HistoricPriceEngine h1 = new HistoricPriceEngine(session);

            h1.GetLongHistoricPrices(symbol1, timeframe, length);

            while (!h1.Complete)
            {
                Thread.Sleep(100);
            }

            HistoricPriceEngine h2 = new HistoricPriceEngine(session);

            h2.GetLongHistoricPrices(symbol2, timeframe, length);

            while (!h2.Complete)
            {
                Thread.Sleep(100);
            }
            //-----------------------

            var dateTimeList = new SortedList <DateTime, int>();

            Quantum q1 = h1.Data;
            Quantum q2 = h2.Data;


            var priceData = new DenseMatrix(2, q1.Data.Count);

            for (int j = 0; j < ((q1.Data.Count <= q2.Data.Count)?q1.Data.Count:q2.Data.Count); j++)
            {
                dateTimeList.Add(q1.Data.Values[j].Time, 1);
                priceData[0, j] = q1.Data.Values[j].BidClose;
                priceData[1, j] = q2.Data.Values[j].BidClose;
            }

            Vector <double> price1 = priceData.Row(0);
            Vector <double> price2 = priceData.Row(1);
            //Statistics.ApplyFunction((DenseVector)price1, Math.Log);
            //Statistics.ApplyFunction((DenseVector)price2, Math.Log);

            DenseVector norm1 = price1.ToArray().NormalizeZScore();
            DenseVector norm2 = price2.ToArray().NormalizeZScore();

            var newsym = new string[] { symbol1, symbol2, "spread" };

            var m = new DenseMatrix(6, norm1.Count);

            m.SetRow(0, norm1);
            m.SetRow(1, norm2);
            m.SetRow(2, (norm1 - norm2).ToArray().NormalizeZScore());

            string filename = symbol1.Replace('/', '_') + "-" + symbol2.Replace('/', '_') + ".html";


            Visualize.GenerateMultiPaneGraph(newsym, dateTimeList.Keys.ToArray(), m, QSConstants.DEFAULT_DATA_FILEPATH + filename,
                                             new ChartOption[] { new ChartOption(), new ChartOption()
                                                                 {
                                                                     Layover = true, YPosition = 0
                                                                 }, new ChartOption()
                                                                 {
                                                                     YPosition = 1
                                                                 } }, null, filename + ".json");

            FileUpload.UploadFileToFTP(QSConstants.DEFAULT_DATA_FILEPATH + filename, filename);
            FileUpload.UploadFileToFTP(QSConstants.DEFAULT_DATA_FILEPATH + filename + ".json", filename + ".json");

            double Spread = m[2, m.ColumnCount - 1];

            if (Spread > 2.0 && m[2, m.ColumnCount - 2] <= 2.0)
            {
                Emailer.SendEmail(symbol1 + "-" + symbol2 + " Spread Above 2.0", "Test");
            }

            if (Spread < -2.0 && m[2, m.ColumnCount - 2] >= -2.0)
            {
                Emailer.SendEmail(symbol1 + "-" + symbol2 + " Spread Below -2.0", "Test");
            }
        }
Пример #21
0
 public void RunJob(FXSession fxsession)
 {
     throw new NotImplementedException();
 }
Пример #22
0
        public static void TestChannelLive(this AbstractChannel ind, string symbol, string timeframe, int length)
        {
            //------------grab data
            FXSession session = new FXSession();
            session.InitializeSession();
            while (!session.LoggedIn)
            {
                Thread.Sleep(100);
            }

            HistoricPriceEngine h = new HistoricPriceEngine(session);
            h.GetLongHistoricPrices(symbol, timeframe, length);

            while (!h.Complete)
            {
                Thread.Sleep(100);
            }
            //-----------------------

            var highList = new List<double>();
            var medList = new List<double>();
            var lowList = new List<double>();

            var dataList = new List<double>();
            var dateTimeList = new SortedList<DateTime, int>();

            Quantum q = h.Data;

            int count = 0;
            foreach (Tick t in q)
            {
                try{

                    ind.HandleNextTick(t);
                    highList.Add(ind.HI(0));
                    medList.Add(ind.MID(0));
                    lowList.Add(ind.LOW(0));

                    dataList.Add(t.BidClose);
                    dateTimeList.Add(t.Time, 1);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                if (count++ > length) break;
            }

            var dz = new DenseMatrix(4, medList.Count);
            dz.SetRow(0, new DenseVector(dataList.ToArray()));
            dz.SetRow(1, new DenseVector(highList.ToArray()));
            dz.SetRow(2, new DenseVector(medList.ToArray()));
            dz.SetRow(3, new DenseVector(lowList.ToArray()));

            Visualize.GenerateMultiPaneGraph(new[] { "data", "high", ind.ToString(), "low" }, dateTimeList.Keys.ToArray(), dz, QSConstants.DEFAULT_DATA_FILEPATH + @"results.html"
                , new ChartOption[]
                {
                    new ChartOption(){Height = 500}, 
                    new ChartOption(){Height = 0, Layover = true, YPosition = 0},
                    new ChartOption(){Height = 0, Layover = true, YPosition = 0},
                    new ChartOption(){Height = 0, Layover = true, YPosition = 0}
                });

            Console.WriteLine("Done Generating Graph for " + ind.ToString());
            }
Пример #23
0
 public SessionStatusListener(FXSession connection)
 {
     _connection = connection;
 }
Пример #24
0
 public static AccountInformationEventArg ProcessData(FXSession connection, O2GResponse response)
 {
     return(new AccountInformationEventArg());
 }
Пример #25
0
 public ResponseListener(FXSession connection)
 {
     _connection = connection;
 }
Пример #26
0
        public static void TestGraphLive(this AbstractIndicator ind, string timeframe, string symbol, int length)
        {
            //------------grab data
            FXSession session = new FXSession();

            session.InitializeSession();

            HistoricPriceEngine h = new HistoricPriceEngine(session);

            h.GetLongHistoricPrices(symbol, timeframe, length);

            while (!h.Complete)
            {
                Thread.Sleep(100);
            }
            //-----------------------

            Quantum       q     = h.Data;
            var           dz    = new DenseMatrix(4 + 1 + ind.SubIndicatorSize, q.Data.Count);
            List <string> names = new List <string>();

            names.Add("symbol");
            names.Add(ind.ToString());
            foreach (var indicator in ind.SubIndicators)
            {
                names.Add(indicator.Key);
            }

            //chartoptions
            ChartOption[] chartOptions = new ChartOption[names.Count];
            chartOptions[0] = new ChartOption()
            {
                Height = 400, YPosition = 0
            };
            chartOptions[1] = new ChartOption()
            {
                Height = 200, YPosition = 1
            };
            for (int i = 2; i < chartOptions.Length; i++)
            {
                chartOptions[i] = new ChartOption()
                {
                    Height = 0, YPosition = 1, Layover = true
                }
            }
            ;

            int counter = 0;

            foreach (Tick tick in q)
            {
                dz[0, counter] = tick.BidOpen;
                dz[1, counter] = tick.BidHigh;
                dz[2, counter] = tick.BidLow;
                dz[3, counter] = tick.BidClose;

                dz[4, counter] = ind.HandleNextTick(tick);

                int icounter = 5;
                foreach (var subind in ind.SubIndicators.Values)
                {
                    dz[icounter, counter] = subind[0];
                    icounter++;
                }

                counter++;
            }


            Visualize.GenerateMultiPaneGraph(names.ToArray(), q.Data.Keys.ToArray(), dz, QSConstants.DEFAULT_DATA_FILEPATH + @"results.html",
                                             chartOptions);

            Console.WriteLine("Done Generating Graph for " + ind.ToString());
        }
Пример #27
0
        private static void Main()
        {


            //TestLiveCointegration.Run();
            /*
            IndicatorMatrix im = new IndicatorMatrix("EUR/USD");
            im.LoadData();
            im.Execute();
            */

            //TestIndicator.TestMA(QSConstants.DEFAULT_DATA_FILEPATH + "GBPUSD15M.xml", 14000, new QSPolyMA(40), new ZLEMA(40));
            //TestIndicator.TestChannelLive(new QSPolyChannel(), "EUR/USD", "m5", 5000 );
            //TestIndicator.TestChannel(new KirshenbaumBands(20), QSConstants.DEFAULT_DATA_FILEPATH + "EURUSD15M.xml", 10000);
            //TestIndicator.TestMA(QSConstants.DEFAULT_DATA_FILEPATH + "EURUSD1H.xml", 15000,  new SMA(25), new DWT(25, 5));
            //TestIndicator.TestGraph(new ReversalGenesis(50),  QSConstants.DEFAULT_DATA_FILEPATH + "AUDUSD1H.xml", 15000);
            //TestIndicator.TestGraph(new HurstIndicator(256), QSConstants.DEFAULT_DATA_FILEPATH + "AUDUSD1H.xml", 15000);
            //TestIndicator.TestGraphLive(new Genesis(30), "m30", "EUR/USD", 10000);
            //TestIndicator.TestGraphLive(new PercentileRank(250, new SMA(200)), "H1", "EUR/USD", 1000);
            //TestIndicator.TestGraphLive(new PercentileRank(250, new SMA(200,new HistoricalVol(50))), "H1", "EUR/USD", 100000);
            //TestIndicator.TestGraphLive(new WilliamsR(), "H1", "EUR/USD", 100000);
            //TestIndicator.TestGraph(new PercentileRank(252, new SMA(251)), QSConstants.DEFAULT_DATA_FILEPATH + "EURUSD1H.xml", 10000);
            Quantum q1 = Quantum.ExcelToQuantum(QSConstants.DEFAULT_DATA_FILEPATH + "EURUSD1H.xml", "EUR/USD");
            Quantum q2 = Quantum.ExcelToQuantum(QSConstants.DEFAULT_DATA_FILEPATH + "GBPUSD1H.xml", "GBP/USD");
            Quantum q3 = Quantum.ExcelToQuantum(QSConstants.DEFAULT_DATA_FILEPATH + "AUDUSD1H.xml", "AUD/USD");
            List<Quantum> lq = new List<Quantum>();
            lq.Add(q1);
            lq.Add(q2);
            lq.Add(q3);
            MultiQuantum mq = MultiQuantum.OrganizeMultiQuantum(lq);
            List <List<Tick>> list = mq.RevertToList();
            double[] dat1 = list[0].ToArray().Select(x => x.BidClose).ToArray().NormalizeZScore();
            double[] dat2 = list[1].ToArray().Select(x => x.BidClose).ToArray().NormalizeZScore();
            double[] dat3 = list[2].ToArray().Select(x => x.BidClose).ToArray().NormalizeZScore();

            DenseVector d11 = new DenseVector(dat1);
            DenseVector d12 = new DenseVector(dat2);
            DenseVector d13 = new DenseVector(dat3);

            DenseVector fe = ((.48 * d11) + (-0.22 * d12) + (-.46 * d13));

            Visualize.GenerateSimpleGraph(fe, "result.html");


            Console.Read();

            Func<Chromosome, double> fitnessFunc = new Func<Chromosome, double>(
                chromosome =>
                {
                    double weight1 = ((RealCodedGene)chromosome[0]).GeneValue;
                    double weight2 = ((RealCodedGene)chromosome[1]).GeneValue;
                    double weight3 = ((RealCodedGene)chromosome[2]).GeneValue;

                    double w1mod = weight1 /(weight1 + weight2 + weight3);
                    double w2mod = weight2 / (weight1 + weight2 + weight3);
                    double w3mod = weight3 / (weight1 + weight2 + weight3);

                    DenseVector d1 = new DenseVector(dat1);
                    DenseVector d2 = new DenseVector(dat2);
                    DenseVector d3 = new DenseVector(dat3);

                    double stdev = ((w1mod * d1) + (w2mod * d2) + (w3mod * d3)).StandardDeviation();

                    return (stdev > 0) ? (1/stdev) : 0.000001;
                }
                );

            Random r = new Random();
            Gene g1 = new RealCodedGene(0, r, new GeneConstraint((x => (double)x < 1.0 && (double)x > -1.0))  {HI = 1.0, LOW = -1.0});
            Gene g2 = new RealCodedGene(0, r, new GeneConstraint((x => (double)x < 1.0 && (double)x > -1.0)) { HI = 1.0, LOW = -1.0 });
            Gene g3 = new RealCodedGene(0, r, new GeneConstraint((x => (double)x < 1.0 && (double)x > -1.0)) { HI = 1.0, LOW = -1.0 });
            List<Gene> cfootprint = new List<Gene>();
            cfootprint.Add(g1);
            cfootprint.Add(g2);
            cfootprint.Add(g3);

            GeneticAlgorithm ga = new GeneticAlgorithm(
                    fitnessFunc,cfootprint, 30, 200, 10
                );

            ga.Run();

            Console.Read();


            var ba1 = new BacktestEngine(0, 3010, true);
            ba1.LoadData(QSConstants.DEFAULT_DATA_FILEPATH + "EURUSD1H.xml", "EUR/USD");
            ba1.LoadData(QSConstants.DEFAULT_DATA_FILEPATH + "GBPUSD1H.xml", "GBP/USD");
            //ba.LoadDataLive("EUR/USD", "m5", 200000);
            //ba.LoadDataLive("GBP/USD", "m5", 20000);
            ba1.OrganizeData();
            ba1.LoadStrategy(new Cointegration());
            ba1.Execute();



            Console.Read();
            

            object[,] denseMatrix;
            ExcelUtil.Open(QSConstants.DEFAULT_DATA_FILEPATH + @"GBPUSD1H.xml", out denseMatrix);

            var mData = new List<double>();

            var predictor = new AC(60);

            for (int i = denseMatrix.GetLength(0); i > 1; i--)
            {
                DateTime dateTime = (DateTime)denseMatrix[i, 1];
                var t = new Tick(
                        0,
                        (double)denseMatrix[i, 6],
                        (double)denseMatrix[i, 7],
                        (double)denseMatrix[i, 8],
                        (double)denseMatrix[i, 9],
                        0,
                        (double)denseMatrix[i, 2],
                        (double)denseMatrix[i, 3],
                        (double)denseMatrix[i, 4],
                        (double)denseMatrix[i, 5],
                        (double)denseMatrix[i, 10],
                        dateTime
                        );

                double d = predictor.HandleNextTick(t);
                if (!d.Equals(double.NaN))
                    mData.Add(d);
            }

            int windowSize = 5;
            int iterations = 10000;
            int trainLength = 5000;
            int validateLength = 1000;
            double[] trainData = mData.ToArray().Take(trainLength).ToArray();
            double[] validateData = mData.ToArray().Skip(trainLength).ToArray().Take(validateLength).ToArray();

            Stage1NeuralNetwork nn = new Stage1NeuralNetwork(windowSize, iterations, trainData, validateData);
            nn.Execute(1);

            NeuralNetworkStrategy nns = new NeuralNetworkStrategy(windowSize) { NeuralNetwork = nn };

            var ba = new BacktestEngine(5000, 9200, true);            
            //ba.LoadData(QSConstants.DEFAULT_DATA_FILEPATH + "GBPUSD15M.xml", "EUR/USD");
            ba.LoadData(QSConstants.DEFAULT_DATA_FILEPATH + "NZDUSD1H.xml", "GBP/USD");
            //ba.LoadDataLive("EUR/USD", "m5", 200000);
            //ba.LoadDataLive("GBP/USD", "m5", 20000);
            ba.OrganizeData();
            ba.LoadStrategy(nns);
            ba.Execute();
            

            Console.Read();

            /*
            Func<Chromosome, double> function = (chromosome =>
            {
                double fitness = 0.001;

                ba.ResetAccount();
                ba.ResetStrategies();
                ba.LoadStrategy(new CustomStrategy(
                       (int)(double)chromosome[0].GeneValue,
                       (int)(double)chromosome[1].GeneValue,
                       (int)(double)chromosome[2].GeneValue,
                       (int)(double)chromosome[3].GeneValue,
                       (int)(double)chromosome[4].GeneValue,
                       (int)(double)chromosome[5].GeneValue,
                       (int)(double)chromosome[6].GeneValue,
                       (int)(double)chromosome[7].GeneValue,
                       (int)(double)chromosome[8].GeneValue
                    ));
                ba.Execute();


                fitness += ba.ret;

                return (fitness > 0) ? fitness : 0.001;
            }
                );

            var GA = new GeneticAlgorithm(function,
                new List<Gene>
                {
                    new Gene(50, new Gene.Constraint(5,200)),
                    new Gene(50, new Gene.Constraint(5,200)),
                    new Gene(50, new Gene.Constraint(5,200)),
                    new Gene(50, new Gene.Constraint(5,500)),
                    new Gene(50, new Gene.Constraint(1,100)),
                    new Gene(50, new Gene.Constraint(1,100)),
                    new Gene(50, new Gene.Constraint(5,500)),
                    new Gene(50, new Gene.Constraint(5,500)),
                    new Gene(50, new Gene.Constraint(1,100))
                }) { Generations = 1000, Trials = 10 }
                ;

            GA.InitializePopulation();
            GA.Run();

            Console.Read();
            */




            /*
            object[,] denseMatrix;
            ExcelUtil.Open(Constants.DEFAULT_DATA_FILEPATH + @"EURUSD1H.xml", out denseMatrix);

            var mData = new List<double>();

            var predictor = new RSI(40);

            for (int i = denseMatrix.GetLength(0); i > 1; i--)
            {
                DateTime dateTime = (DateTime) denseMatrix[i, 1];
                var t = new Tick(
                        0,
                        (double) denseMatrix[i, 6],
                        (double) denseMatrix[i, 7],
                        (double) denseMatrix[i, 8],
                        (double) denseMatrix[i, 9],
                        0,
                        (double) denseMatrix[i, 2],
                        (double) denseMatrix[i, 3],
                        (double) denseMatrix[i, 4],
                        (double) denseMatrix[i, 5],
                        (double) denseMatrix[i, 10],
                        dateTime
                        );

                double d = predictor.HandleNextTick(t);
                if (!d.Equals(double.NaN))
                    mData.Add(d);
            }

            int windowSize = 5;
            int iterations = 5000;
            int trainLength = 5000;
            int validateLength = 1000;
            double[] trainData = mData.ToArray().Take(trainLength).ToArray();
            double[] validateData = mData.ToArray().Skip(trainLength).ToArray().Take(validateLength).ToArray();

            Stage1NeuralNetwork nn = new Stage1NeuralNetwork(windowSize, iterations, trainData, validateData);
            nn.Execute(1);

            NeuralNetworkStrategy nns = new NeuralNetworkStrategy(windowSize){NeuralNetwork = nn};
            */

            /*
            bool seao = true;
            if (seao)
            { 

                var ba = new BacktestEngine(0, 50000, true);
                ba.LoadDataLive("EUR/USD", "m30", 80000);
                
                //ba.LoadStrategy(nns);
                ba.LoadStrategy(new RSIEntry(50){LongEntry = 60, ShortEntry = 40});
                ba.LoadStrategy(new RSIExit(50){ LongExit = 70, ShortExit = 30 });

                //ba.LoadStrategy(new Pyramid(.1, .05, .001));
                ba.Execute();

                Console.Read();
            }

            BacktestEngine[] barray = new BacktestEngine[2];

            Func<Chromosome, double> function = (chromosome =>
            {
                double fitness = 0.001;
                foreach (BacktestEngine bx in barray)
                {
                    bx.ResetAccount();
                    bx.ResetStrategies();
                    bx.LoadStrategy(new CustomStrategy());
                    bx.LoadStrategy(new Pyramid((double) chromosome[0].GeneValue,
                        (double) chromosome[1].GeneValue,
                        (double) chromosome[2].GeneValue));
                    bx.Execute();

                    if (bx.ret > 100)
                        fitness += 100;
                    else
                        fitness += bx.ret;
                }

                return (fitness > 0) ? fitness/5 : 0.001;
            }
                );

            var GA = new GeneticAlgorithm(function,
                new List<Gene>
                {
                    new Gene(5, new Gene.Constraint(0,1.0)),
                    new Gene(5, new Gene.Constraint(0,1.0)),
                    new Gene(5, new Gene.Constraint(0,1.0/100.0))
                }) {Generations = 1000, Trials = 1}
                ;

            GA.InitializePopulation();
            GA.Run();

            Console.Read();

            /*
            b.Output = true;
            b.ResetAccount();
            b.ResetStrategies();
            b.LoadStrategy(new RSIEntry()
            {
                EntryTarget1 = (double)GA.maxC[0].GeneValue,
                EntryTarget2 = (double)GA.maxC[1].GeneValue
            });
            b.LoadStrategy(new RSIExit()
            {
                ExitTarget1 = (double)GA.maxC[2].GeneValue,
                ExitTarget2 = (double)GA.maxC[3].GeneValue
            });
            

            b.Execute();
            */
            //Console.Read();
            
        
            //object[,] data;

            /*
            ExcelUtil.Open("C:\\Users\\EL65628\\Work\\QuantSys\\data\\UCUM.xls", out data);
            DenseMatrix d = ExcelUtil.ToMatrix(data, 2, 1283, 1, 2, true);

            DenseVector normchf = Statistics.NormalizeZScore(d.Column(0).ToArray());
            DenseVector normmxn = Statistics.NormalizeZScore(d.Column(1).ToArray());

            DenseVector kurtmxn = new DenseVector(Statistics.AggregateWindow(d.Column(1).ToArray(),
                Statistics.Kurtosis, 50, false, false));
            
            DenseVector corre = new DenseVector((Statistics.AggregateWindow(
                Statistics.RawRateOfReturn(d.Column(0).ToArray()),
                Statistics.RawRateOfReturn(d.Column(1).ToArray()), 
                Statistics.Correlation,
                80, false, true)));

            //DenseMatrix dNew = new DenseMatrix(3, 1282);
            //dNew.SetRow(0, (DenseVector)d.Column(0).Normalize(100));
            //dNew.SetRow(1, (DenseVector)d.Column(1).Normalize(100));
            //dNew.SetRow(2, corre);

            Visualize.GenerateGraph(corre, "C:\\Users\\EL65628\\Work\\QuantSys\\data\\correlation.html");
            Visualize.GenerateGraph(kurtmxn, "C:\\Users\\EL65628\\Work\\QuantSys\\data\\kurtosis.html");
            //Visualize.GenerateGraph(normmxn, "C:\\Users\\EL65628\\Work\\QuantSys\\data\\diff2.html");
            Visualize.GenerateGraph((DenseVector)(Statistics.NormalizeZScore((-1.5 * normmxn + .9 * normchf).ToArray())), "C:\\Users\\EL65628\\Work\\QuantSys\\data\\diff3.html");

            string[] symbols = { "usd/chf", "usd/mxn" ,"correlation"};
            //Visualize.GenerateMultiSymbolGraph(symbols, dNew, new DateTime(), new TimeSpan(1, 0, 0), "C:\\Users\\EL65628\\Work\\QuantSys\\data\\diff.html");
           
            
            int[] vectors = { 5, 3, 2, 4, 6, 7, 8, 9, 10, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54 };

            string vecstring = "1 0 0 0 1 0 1 1 0 0 0 0 1 0 1 0 1 1 1 1 1 0 1 1 1 0 0 0 1 1 1 0 0 0 1 0 0 0 0 1 1 1 1 0 0 0 1 1 0";


            string[] vectemp = vecstring.Split(' ');
            List<int> vec = new List<int>();

            for (int i = 0; i < vectors.Length; i++)
            {
                if (vectemp[i]=="1") vec.Add(vectors[i]);
            }

            //int[] vect = {13, 19, 25, 27 };
            int[] vect = { 17, 18, 22, 27, 40, 49};

            ExcelUtil.Open("C:\\Users\\EL65628\\Work\\QuantSys\\data\\EURUSD1D.xml", out data);
            TwoStageNN twoStageNn = new TwoStageNN(50, 200, data, vect);
            twoStageNn.Execute();
            

            //GeneticAlgorithm g = new GeneticAlgorithm();
            //g.Run();

            Console.ReadLine();

            PortfolioOptimizer.Run();
            */

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            string[] currencies =
            {
                "EUR/USD",
                "GBP/USD",
                "USD/CAD",
                "USD/CHF",
                "AUD/USD",
                "NZD/USD",
                "USD/JPY",
                "USD/MXN",
                "USD/ZAR",
                "USD/PLN",
                "USD/TRY",
                "USD/DKK",
                "USD/SEK",
                "USD/NOK"
            };

            var currencypairs = new List<string[]>();


            for (int i = 0; i < currencies.Length; i++)
            {
                for (int j = 0; j < i; j++)
                {
                    if (currencies[i] != currencies[j])
                    {
                        string[] temp = {currencies[i], currencies[j]};
                        currencypairs.Add(temp);
                        Console.WriteLine(currencies[i] + " " + currencies[j]);
                    }
                }
            }


            /////////////////////////////////////////////////////////
            /*
            FXSession fxsession1 = new FXSession();

            string[] tempgroup = { "AUD/USD", "NZD/USD" };

            Thread oThread1 = new Thread(new ThreadStart(fxsession1.InitializeSession));
            oThread1.Start();

            while (fxsession1.LoginStatus.Equals(FXSession.LOGIN_STATUS.NOT_LOGGED_IN))
            {
                Thread.Sleep(1000);
                Console.Write(".");
            }

            if (fxsession1.LoginStatus.Equals(FXSession.LOGIN_STATUS.LOGGED_IN))
            {
                //Job_SymbolSet job = new Job_SymbolSet(ex, "H1", 150, new EMA(14));
                //Job_CorrelationMatrix job = new Job_CorrelationMatrix(currencies, "D1", 300, Job_CorrelationMatrix.CovarianceType.RawReturn);

                Job_Cointegration job = new Job_Cointegration(tempgroup, "m30", 300);
                    fxsession1.PlaceJob(job);
                    job.RunJob(fxsession1);
                    Thread.Sleep(1000);
            }

            Console.ReadLine();
            
            */
            //////////////////////////////////////////////////////////////////

            while (true)
            {
                try
                {
                    var fxsession = new FXSession();


                    var oThread = new Thread(fxsession.InitializeSession);
                    oThread.Start();

                    while (!fxsession.LoggedIn)
                    {
                        Thread.Sleep(1000);
                        Console.Write(".");
                    }

                    if (fxsession.LoggedIn)
                    {
                        //Job_SymbolSet job = new Job_SymbolSet(ex, "H1", 150, new EMA(14));
                        //Job_CorrelationMatrix job = new Job_CorrelationMatrix(currencies, "D1", 300, Job_CorrelationMatrix.CovarianceType.RawReturn);

                        //Job_Cointegration.Process(fxsession, "USD/DKK", "USD/CHF", "m30", 3000);
                        //Console.Read();

                        foreach (var group in currencypairs)
                        {
                            if ((!group[0].Substring(0, 3).Equals("USD") && !group[1].Substring(0, 3).Equals("USD")) ||
                                (group[0].Substring(0, 3).Equals("USD") && group[1].Substring(0, 3).Equals("USD")))
                            {

                                try
                                {
                                    Job_Cointegration.Process(fxsession, group[0], group[1], "m30", 3000);
                                    Thread.Sleep(1000);
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e.Message);
                                }
                            }
                        }
                    }

                    fxsession.EndSession();
                    oThread.Abort();
                }

                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                Console.WriteLine(DateTime.Now.ToString());

                Thread.Sleep(1000*60*30);
            }

            Console.ReadLine();
        }
Пример #28
0
        public static void TestChannelLive(this AbstractChannel ind, string symbol, string timeframe, int length)
        {
            //------------grab data
            FXSession session = new FXSession();

            session.InitializeSession();
            while (!session.LoggedIn)
            {
                Thread.Sleep(100);
            }

            HistoricPriceEngine h = new HistoricPriceEngine(session);

            h.GetLongHistoricPrices(symbol, timeframe, length);

            while (!h.Complete)
            {
                Thread.Sleep(100);
            }
            //-----------------------

            var highList = new List <double>();
            var medList  = new List <double>();
            var lowList  = new List <double>();

            var dataList     = new List <double>();
            var dateTimeList = new SortedList <DateTime, int>();

            Quantum q = h.Data;

            int count = 0;

            foreach (Tick t in q)
            {
                try{
                    ind.HandleNextTick(t);
                    highList.Add(ind.HI(0));
                    medList.Add(ind.MID(0));
                    lowList.Add(ind.LOW(0));

                    dataList.Add(t.BidClose);
                    dateTimeList.Add(t.Time, 1);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                if (count++ > length)
                {
                    break;
                }
            }

            var dz = new DenseMatrix(4, medList.Count);

            dz.SetRow(0, new DenseVector(dataList.ToArray()));
            dz.SetRow(1, new DenseVector(highList.ToArray()));
            dz.SetRow(2, new DenseVector(medList.ToArray()));
            dz.SetRow(3, new DenseVector(lowList.ToArray()));

            Visualize.GenerateMultiPaneGraph(new[] { "data", "high", ind.ToString(), "low" }, dateTimeList.Keys.ToArray(), dz, QSConstants.DEFAULT_DATA_FILEPATH + @"results.html"
                                             , new ChartOption[]
            {
                new ChartOption()
                {
                    Height = 500
                },
                new ChartOption()
                {
                    Height = 0, Layover = true, YPosition = 0
                },
                new ChartOption()
                {
                    Height = 0, Layover = true, YPosition = 0
                },
                new ChartOption()
                {
                    Height = 0, Layover = true, YPosition = 0
                }
            });

            Console.WriteLine("Done Generating Graph for " + ind.ToString());
        }
Пример #29
0
 public ResponseListener(FXSession connection)
 {
     _connection = connection;
 }