public AzioneSelezioneDestra(Quantum quantum, Casella casellaPartenza)
        {
            this.casellaPartenza = casellaPartenza;
            this.quantum = quantum;
            naveUsata = casellaPartenza.Occupante;

            GuiManager gui = quantum.getGUI();
            gui.Tabellone.ResetSelezioneMouse();
            gui.Tabellone.MostraSelezione = false;

            // HACK: gestire in maniera sensata  e più agile il posizionamento dei Widget
            // (magari con un costruttore nuovo a cui si passa invece di solo un punto qualche informazione in più per posizionarsi?)
            // P.S: se ne è occupato Mirco! Ci metterà mano lui
            Vector2 pos1 = gui.Tabellone.Tile2Pixel(this.casellaPartenza);
            Vector2 pos2 = pos1;
            var lato = gui.Tabellone.LatoCasella;

            pos1 -= new Vector2(20 - lato / 2, 15);
            pos2 += new Vector2(20 + lato / 2, -15);

            bool puòRiconfig = !naveUsata.Riconfigurata;
            bool puòUsareSpecial = !naveUsata.SpecialUsata && checkSpecial(naveUsata);

            Riconfig = new Widget(pos1, doveDisegnoWidget.sinistra, widget.Riconfigura, puòRiconfig);
            Special = new Widget(pos2, doveDisegnoWidget.destra, widget.UsaSpecial, puòUsareSpecial);

            Riconfig.Click += riconfigura;
            Special.Click += usaSpecial;
            gui.Iscrivi(Riconfig);
            gui.Iscrivi(Special);
        }
        public AzioneMovimento(Quantum quantum, Casella casellaPartenza, bool puòAttaccare = true)
        {
            this.casellaPartenza = casellaPartenza;
            naveMossa = casellaPartenza.Occupante;
            this.quantum = quantum;
            this.puòAttaccare = puòAttaccare;

            // Faccio partire il pathfinder
            pathFinder = new PathFinder();
            pathFinder.Start(this.casellaPartenza, naveMossa.MuoveInDiagonale);

            // Illumino le caselle raggiungibili
            int[] caselleRaggiungibili =

                Tile.Tiles(t =>
                {
                    Casella casella = t as Casella;
                    int d = pathFinder.DistanzaCasella(t);
                    return (d <= naveMossa.Pwr && d > 0 && (puòAttaccare || (casella != null && casella.Occupante == null) ));
                }
                ).Select(t => t.ID).ToArray();

            quantum.getGUI().Tabellone.ResetSelezioneMouse();
            quantum.getGUI().Tabellone.IlluminaCaselle(caselleRaggiungibili);
        }
 public HistoricPriceEngine(FXSession session)
 {
     _mktData         = new Quantum();
     _completeCounter = 0;
     complete         = false;
     mHandler         = HistoricDataReceived;
     this.session     = session;
 }
Exemple #4
0
 public HistoricPriceEngine(FXSession session)
 {
     _mktData = new Quantum();
     _completeCounter = 0;
     complete = false;
     mHandler = HistoricDataReceived;
     this.session = session;
 }
Exemple #5
0
 public SwarmSize(int maxDimensions)
 {
     max = new double[maxDimensions];
     maxInit = new double[maxDimensions];
     min = new double[maxDimensions];
     minInit = new double[maxDimensions];
     q=new Quantum(maxDimensions);
 }
 // Costruttore PRIVATO semplificato (le caselle disponibili sono quelle intorno ad un pianeta colonizzato)
 private AzionePiazzaNave(Quantum quantum, Nave nave)
     : this(quantum, nave, Tile.Tiles(tile =>
     {
         Casella casella = tile as Casella;
         return
         casella?.PianetaPiùVicino(compreseDiagonali: true)?.PresenzaAlleata(nave) == true
         && casella.Occupante == null;
     }).Select(t => (Casella)t).ToArray())
 {
 }
Exemple #7
0
 public Surface2D(Quantum width, Quantum height, Color bgColor)
 {
     _bgColor = bgColor;
     Width    = width.Value;
     Height   = height.Value;
     hBitMap  = (Width > 0 && Height > 0)
         ? new Bitmap(Width, Height,
                      PixelFormat.Format24bppRgb)
         : null;
 }
Exemple #8
0
        public static void TestMA(string filename, int length, params AbstractIndicator[] ind)
        {
            Quantum q = Quantum.ExcelToQuantum(filename, "symbol", 0);

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

            names.Add("symbol");
            foreach (var indicator in ind)
            {
                names.Add(indicator.toString());
            }

            //chartoptions
            ChartOption[] chartOptions = new ChartOption[names.Count];
            chartOptions[0] = new ChartOption()
            {
                Height = 500, YPosition = 0
            };
            for (int i = 1; i < chartOptions.Length; i++)
            {
                chartOptions[i] = new ChartOption()
                {
                    Height = 0, YPosition = 0, 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;


                int icounter = 4;
                foreach (var subind in ind)
                {
                    subind.HandleNextTick(tick);
                    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());
        }
Exemple #9
0
 void GenerateQuantums(int Quantity, ChemEObject StartPosition)
 {
     for (int i = 1; i <= Quantity; i++)
     {
         Quantum newQuantum = new Quantum {
             Position = StartPosition
         };
         AllQuantums.Add(newQuantum);
         StartPosition.Quantums.Add(newQuantum);
     }
 }
            public void ShouldInitializeTheProperties()
            {
                var color     = new MagickColor(Quantum.Max, (QuantumType)(Quantum.Max * 0.75), (QuantumType)(Quantum.Max * 0.5), (QuantumType)(Quantum.Max * 0.25));
                var cmykColor = ColorCMYK.FromMagickColor(color);

                Assert.InRange(Quantum.ScaleToDouble(cmykColor.C), 0.99, 1.0);
                Assert.InRange(Quantum.ScaleToDouble(cmykColor.M), 0.74, 0.75);
                Assert.InRange(Quantum.ScaleToDouble(cmykColor.Y), 0.49, 0.5);
                Assert.InRange(Quantum.ScaleToDouble(cmykColor.K), 0.0, 0.01);
                Assert.InRange(Quantum.ScaleToDouble(cmykColor.A), 0.24, 0.25);
            }
 /// <summary>
 /// Azione per piazzare una nave dova clicca il giocatore
 /// </summary>
 public AzionePiazzaNave(Quantum quantum, Nave naveDaPiazzare, Casella[] caselleDisponibili)
 {
     // Piazzo una Nave in una casella arbitraria fra quelle dell'argomento
     this.quantum = quantum;
     this.caselleDisponibili = caselleDisponibili;
     this.naveDaPiazzare = naveDaPiazzare;
     quantum.getGUI().Tabellone.ResetSelezioneMouse();
     if (!caselleDisponibili.Any())
     {
         Interfaccia.ConsoleMessaggi.NuovoMessaggio("Impossibile piazzare la nave!", Color.Salmon);
         Cleanup();
     }
 }
        public AzioneSpecialDestroyer(Quantum quantum, Casella casellaPartenza)
        {
            _partenza = casellaPartenza;
            this.quantum = quantum;
            _naveMossa = casellaPartenza.Occupante;

            int[] disponibili =
                Tile.Tiles(t => t.PresenzaAlleata(quantum.getGestoreDiGiocatori().getGiocatoreDiTurno())).Select(t => t.ID).ToArray();

            quantum.getGUI().Tabellone.IlluminaCaselle(disponibili);
            quantum.getGUI().Tabellone.ResetSelezioneMouse();
            Interfaccia.ConsoleMessaggi.NuovoMessaggio("Scegli l'alleato con cui fare il warp:");
        }
        public AzioneSpecialFlagship(Quantum quantum, Casella casellaPartenza)
        {
            this.quantum = quantum;
            this.casellaFlagship = casellaPartenza;
            flagship = casellaPartenza.Occupante;

            // Selezione caselle da illuminare
            Func<Tile, bool> filtraAlleati = (t => t.EunaCasella && t.PresenzaAlleata(flagship));

            int[] tiles = Tile.IdTiles(filtraAlleati);
            int[] caselle = tiles.Where(t => { return casellaFlagship.Adiacente(t, true); }).ToArray();

            quantum.getGUI().Tabellone.IlluminaCaselle(caselle);
            fase = sceltaAlleato;
            Interfaccia.ConsoleMessaggi.NuovoMessaggio("Clicca su un alleato adiacente");
        }
        public AzioneSpecialBattlestation(Quantum quantum, Casella posizioneIniziale)
        {
            this.quantum = quantum;
            this.posizione = posizioneIniziale;
            this.nave = posizione.Occupante;

            var bersagli = Tile.Tiles(
                (Tile t) =>
                {
                    var c = t as Casella;
                    return c?.Adiacente(posizione, false) == true && c?.Occupante?.Alleato(quantum.getGestoreDiGiocatori().getGiocatoreDiTurno()) == false;

                }).Select(c => c.ID).ToArray();

            quantum.getGUI().Tabellone.IlluminaCaselle(bersagli);
            quantum.getGUI().Tabellone.ResetSelezioneMouse();
            ConsoleMessaggi.NuovoMessaggio("Scegli l'avversario da attaccare");
        }
        public AzioneSelezionePianeta(Quantum quantum, Pianeta pianeta)
        {
            this.quantum = quantum;
            this.pianeta = pianeta;

            GuiManager gui = quantum.getGUI();

            Vector2 pos = gui.Tabellone.Tile2Pixel(pianeta);

            pos += new Vector2(gui.Tabellone.LatoCasella / 2, - gui.Tabellone.LatoCasella / 3);

            colonizza = new Widget(pos, doveDisegnoWidget.destra, widget.Colonizza, pianeta.Colonizzabile(quantum.getGestoreDiGiocatori().getGiocatoreDiTurno()));

            colonizza.Click += Colonizza;
            gui.Iscrivi(colonizza);
            gui.Tabellone.ResetSelezioneMouse();
            gui.Tabellone.MostraSelezione = false;
        }
Exemple #16
0
        public void GetLongHistoricPrices(string symbol, string timeframe, int ticks)
        {
            _mktData = new Quantum();
            Symbol = new Symbol(symbol);
            session.AttachHandler(mHandler);

            DateTime dateNow = DateTime.Now;
            TimeSpan time = Timeframe.StringToTimeSpan(timeframe);

            DateTime startDate = dateNow.AddMinutes(-ticks * Timeframe.TimeframeToMinutes(timeframe));

            O2GRequestFactory factory = session.Session.getRequestFactory();
            O2GTimeframeCollection timeframes = factory.Timeframes;
            O2GTimeframe tfo = timeframes[timeframe];
            
            int counter = ticks;

            lock (locker)
            {
                while (counter > 0)
                {

                    _completeCounter++;
                    int subticks = (counter >= QSConstants.MAX_FXCM_API_TICKS)
                        ? QSConstants.MAX_FXCM_API_TICKS
                        : counter;
                    O2GRequest request = factory.createMarketDataSnapshotRequestInstrument(symbol, tfo, subticks);
                    factory.fillMarketDataSnapshotRequestTime(request, startDate,
                        startDate.AddMinutes(2*subticks*Timeframe.TimeframeToMinutes(timeframe)));
                    session.Session.sendRequest(request);

                    startDate = startDate.AddMinutes(subticks*Timeframe.TimeframeToMinutes(timeframe));
                    counter -= (counter >= QSConstants.MAX_FXCM_API_TICKS) ? QSConstants.MAX_FXCM_API_TICKS : counter;
                }
            }

            int timeCounter = 0;
            while (!Complete || timeCounter++ < 3000) //max timeout 30 seconds
            {
                Thread.Sleep(100);
            }

        }
        public void GetLongHistoricPrices(string symbol, string timeframe, int ticks)
        {
            _mktData = new Quantum();
            Symbol   = new Symbol(symbol);
            session.AttachHandler(mHandler);

            DateTime dateNow = DateTime.Now;
            TimeSpan time    = Timeframe.StringToTimeSpan(timeframe);

            DateTime startDate = dateNow.AddMinutes(-ticks * Timeframe.TimeframeToMinutes(timeframe));

            O2GRequestFactory      factory    = session.Session.getRequestFactory();
            O2GTimeframeCollection timeframes = factory.Timeframes;
            O2GTimeframe           tfo        = timeframes[timeframe];

            int counter = ticks;

            lock (locker)
            {
                while (counter > 0)
                {
                    _completeCounter++;
                    int subticks = (counter >= QSConstants.MAX_FXCM_API_TICKS)
                        ? QSConstants.MAX_FXCM_API_TICKS
                        : counter;
                    O2GRequest request = factory.createMarketDataSnapshotRequestInstrument(symbol, tfo, subticks);
                    factory.fillMarketDataSnapshotRequestTime(request, startDate,
                                                              startDate.AddMinutes(2 * subticks * Timeframe.TimeframeToMinutes(timeframe)));
                    session.Session.sendRequest(request);

                    startDate = startDate.AddMinutes(subticks * Timeframe.TimeframeToMinutes(timeframe));
                    counter  -= (counter >= QSConstants.MAX_FXCM_API_TICKS) ? QSConstants.MAX_FXCM_API_TICKS : counter;
                }
            }

            int timeCounter = 0;

            while (!Complete || timeCounter++ < 3000) //max timeout 30 seconds
            {
                Thread.Sleep(100);
            }
        }
        public AzioneInizioPartitaOffLine(Quantum quantum)
        {
            //EDIT: faccio tutto nel costruttore, tanto è una botta e via questa
            //REPLY: OK! Se il problema è che ti sta scomodo passare quantum, questa azione necessita
            // solo di GestoreDiAzioni e GestoreDiGiocatori per funzionare (in termini di memoria sono solo due liste, molto ragionevole).
            //Quindi si puo' costruirla come public AzioneInizioPartitaOffLine(GestoreDiAzioni a, GestoreDiGiocatori b).
            //Probabilmente vale anche per le altre azioni, avevo messo quantum in via provvisoria
            //EDIT2: serve anche la GUI a meno di non attivare i bottoni in qualche altro modo

            quantum.getGestoreDiAzioni().IncodaAzione(new AzioneStampaAConsole("Partita iniziata!"));

            foreach (Bottone b in quantum.getGUI().Bottoni)
            {
                b.Click += b.associatedEvent;
            }
            //probabilmente ha senso creare un'azione di inizio turno (che verrà usata anche dal bottone passa turno)
            quantum.getGestoreDiGiocatori().getGiocatoreDiTurno().Init();
            quantum.getGestoreDiAzioni().IncodaAzione(new AzioneSelezione(quantum));
            Cleanup();
        }
Exemple #19
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))));
            }
        }
Exemple #20
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)));
            }
        }
Exemple #21
0
        //float pos = 0f;
        //Curve percorsoX;
        //Curve percorsoY;
        public Movimento(Quantum quantum, Nave naveMossa, Casella[] percorso)
        {
            // Avevo provato ad usare le curve, ma è un po' difficile (bisogna settare tutte le tangenti una per una)
            // e forse, con il tabellone quadrato, non viene nemmeno bene
            // però, con i percorsi dritti, viene un po' troppo squadrato
            // qualche idea?

            //percorsoX = new Curve();
            //percorsoY = new Curve();
            //float i = 0;
            //float n = percorso.Length;
            //foreach (var p in percorso)
            //{
            //    percorsoX.Keys.Add(new CurveKey(i / n, p.X));
            //    percorsoY.Keys.Add(new CurveKey(i / n, p.X));
            //    i++;

            //}
            this.quantum = quantum;
            this.naveMossa = naveMossa;
            _percorso = percorso.Select(casella => quantum.getGUI().Tabellone.Tile2Pixel(casella)).ToArray();
            lungh = percorso.Length;
        }
 private void setData(clsProceso P)
 {
     if (P != null)
     {
         txtOp.Text      = P.Operacion;
         txtNumero.Text  = P.Numero.ToString();
         txtTME.Text     = P.TME.ToString();
         txtTT.Text      = (P.TME - P.TR).ToString();
         txtTR.Text      = (P.TR).ToString();
         lblQuantum.Text = Quantum.ToString();
     }
     else
     {
         txtOp.Text      = "";
         txtNumero.Text  = "";
         txtTME.Text     = "";
         txtTT.Text      = "";
         txtTR.Text      = "";
         lblQuantum.Text = "";
     }
     dgActual.DataSource     = SetListos(ProcesosListos);
     dgConcluidos.DataSource = SetConcluidos(Concluidos);
     DrawPages();
 }
 public AzioneSelezione(Quantum quantum)
 {
     this.quantum = quantum;
 }
 /// <summary>
 /// Costruttore statico per piazzare navi dal cimitero
 /// </summary>
 public static Azione DaRiserva(Quantum quantum, Nave nave)
 {
     return new AzionePiazzaNave(quantum, nave) { obbligatoria = false, consumaAzione = true };
 }
Exemple #25
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());
        }
Exemple #26
0
 public MarketDataEventArg()
 {
     data = new Quantum();
 }
 public AzioneSetupPartitaOffLine(Quantum quantum, int numeroGiocatori)
 {
     this.quantum = quantum;
     this.numeroGiocatori = numeroGiocatori;
 }
 public void Reset()
 {
     _mktData         = new Quantum();
     _completeCounter = 0;
     complete         = false;
 }
Exemple #29
0
 public Cimitero(Quantum quantum, Riquadro contenitore)
     : base(contenitore)
 {
     this.quantum = quantum;
 }
 public AzioneFineTurno(Quantum quantum)
 {
     this.quantum = quantum;
 }
Exemple #31
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());
        }
Exemple #32
0
        public static void TestChannel(this AbstractChannel ind, string filename, int length)
        {
            Quantum q = Quantum.ExcelToQuantum(filename, "symbol", 0);

            var dz = new DenseMatrix(4 + 3, q.Data.Count);

            List <string> names = new List <string>();

            names.Add("symbol");
            names.Add("HIGH");
            names.Add(ind.ToString());
            names.Add("LOW");

            //chartoptions
            ChartOption[] chartOptions = new ChartOption[names.Count];
            chartOptions[0] = new ChartOption()
            {
                Height = 500, YPosition = 0
            };
            chartOptions[1] = new ChartOption()
            {
                Height = 0, YPosition = 0, Layover = true
            };
            chartOptions[2] = new ChartOption()
            {
                Height = 0, YPosition = 0, Layover = true
            };
            chartOptions[3] = new ChartOption()
            {
                Height = 0, YPosition = 0, Layover = true
            };

            int counter = 0;

            foreach (Tick tick in q)
            {
                ind.HandleNextTick(tick);
                dz[0, counter] = tick.BidOpen;
                dz[1, counter] = tick.BidHigh;
                dz[2, counter] = tick.BidLow;
                dz[3, counter] = tick.BidClose;
                dz[4, counter] = ind.HI(0);
                dz[5, counter] = ind.MID(0);
                dz[6, counter] = ind.LOW(0);

                counter++;
            }

            Visualize.GenerateMultiPaneGraph(new[] { "data", "high", ind.ToString(), "low" }, q.Data.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());
        }
Exemple #33
0
 public MarketDataEventArg()
 {
     data = new Quantum();
 }
Exemple #34
0
        public async Task Handle(ReduceMetrics e, IMessageHandlerContext ctx)
        {
            var updated = _updatedNames.ToList();

            _updatedNames = new ConcurrentBag <string>();

            foreach (var update in updated)
            {
                var timeDbId = new RiakObjectId("default", "Timeseries", update);

                var options = new RiakGetOptions {
                    BasicQuorum = true, NotFoundOk = false
                };
                options.SetRw(Quorum.WellKnown.Quorum);
                _logger.Debug("Getting timeseries db of id {0}", timeDbId.Key);
                var result = await _client.Async.Get(timeDbId, options).ConfigureAwait(false);

                if (!result.IsSuccess)
                {
                    continue;
                }

                var timedb   = result.Value.GetObject <IEnumerable <Quantum> >();
                var directs  = timedb.Where(x => x.Duration == "x");
                var timeDiff = TimeSpan.FromSeconds(directs.Select(x => x.Timestamp).Aggregate((cur, next) => Math.Abs(cur - next)) / directs.Count());


                var levelOneBucket = TimeSpan.FromMinutes(timeDiff.Seconds);
                {
                    var tooOld   = DateTime.UtcNow.ToUnix() - (levelOneBucket.Seconds * 500);
                    var levelOne = timedb.Where(x => x.Duration == "x" && x.Timestamp < tooOld);

                    var toAddOrUpdate = new List <Quantum>();
                    _logger.Debug("Reducing {0} metrics into buckets {1}m", levelOne.Count(), levelOneBucket.TotalMinutes);
                    foreach (var group in levelOne.GroupBy(x => new { Bucket = x.Timestamp % levelOneBucket.Seconds, Tags = x.Tags }))
                    {
                        var quantum = new Quantum
                        {
                            Timestamp = group.First().Timestamp,
                            Duration  = $"{levelOneBucket.TotalMinutes}m",
                            Name      = update,
                            Value     = group.Average(x => x.Value),
                            Count     = group.Count(),
                            Tags      = group.Key.Tags
                        };
                        toAddOrUpdate.Add(quantum);
                    }

                    var success = await UpdateTimeDb(update, (db) =>
                    {
                        levelOne.ForEach(x => db = db.TryRemove(x, y => y.Id));

                        foreach (var toadd in toAddOrUpdate)
                        {
                            var existing = db.SingleOrDefault(x => x.Id == toadd.Id);
                            if (existing == null)
                            {
                                db = db.Add(toadd);
                            }
                            else
                            {
                                existing.Value  = ((existing.Value * existing.Count) + (toadd.Value * toadd.Count)) / (existing.Count + toadd.Count);
                                existing.Count += toadd.Count;
                            }
                        }
                        return(db);
                    });

                    if (!success)
                    {
                        _logger.Warn("Failed to reduce {0} metrics into buckets {1}m", levelOne.Count(), levelOneBucket.TotalMinutes);
                    }
                }
                var levelTwoBucket = TimeSpan.FromHours(timeDiff.Seconds);
                {
                    var tooOld   = DateTime.UtcNow.ToUnix() - (levelTwoBucket.Seconds * 500);
                    var levelTwo = timedb.Where(x => x.Duration != $"{levelTwoBucket.TotalHours}h" && x.Timestamp < tooOld);

                    var toAddOrUpdate = new List <Quantum>();
                    _logger.Debug("Reducing {0} metrics into buckets {1}h", levelTwo.Count(), levelTwoBucket.TotalHours);
                    foreach (var group in levelTwo.GroupBy(x => new { Bucket = x.Timestamp % levelTwoBucket.Seconds, Tags = x.Tags }))
                    {
                        var quantum = new Quantum
                        {
                            Timestamp = group.First().Timestamp,
                            Duration  = $"{levelTwoBucket.TotalHours}h",
                            Name      = update,
                            Value     = group.Average(x => x.Value),
                            Count     = group.Count(),
                            Tags      = group.Key.Tags
                        };
                        toAddOrUpdate.Add(quantum);
                    }
                    var success = await UpdateTimeDb(update, (db) =>
                    {
                        levelTwo.ForEach(x => db = db.TryRemove(x, y => y.Id));

                        foreach (var toadd in toAddOrUpdate)
                        {
                            var existing = db.SingleOrDefault(x => x.Id == toadd.Id);
                            if (existing == null)
                            {
                                db = db.Add(toadd);
                            }
                            else
                            {
                                existing.Value  = ((existing.Value * existing.Count) + (toadd.Value * toadd.Count)) / (existing.Count + toadd.Count);
                                existing.Count += toadd.Count;
                            }
                        }
                        return(db);
                    });

                    if (!success)
                    {
                        _logger.Warn("Failed to reduce {0} metrics into buckets {1}h", levelTwo.Count(), levelTwoBucket.TotalHours);
                    }
                }
            }
        }
Exemple #35
0
        public void LoadData(string filename, string symbol)
        {
            Quantum q = Quantum.ExcelToQuantum(filename, symbol, _dataStart);

            _dataSet.Add(q);
        }
Exemple #36
0
 public void AddQuantum(Quantum pQuantum)
 {
     _Data.Add(pQuantum);
 }
Exemple #37
0
 public void Reset()
 {
     _mktData = new Quantum();
     _completeCounter = 0;
     complete = false;
 }
Exemple #38
0
        public override string ToString()
        {
            string quantumStr = Quantum.ToString();

            return(String.Format("{0} {1}{2}", Length, quantumStr.Remove(quantumStr.Length - 1).ToLower(), Length > 1 ? "s" : String.Empty));
        }
Exemple #39
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();
        }
 public SchermateDiGioco(Quantum quantum)
 {
     this.quantum = quantum;
 }
Exemple #41
0
 void ITimestamp.Quantum(Quantum quantum) => _quantum = quantum;
Exemple #42
0
 public MarketDataEventArg(Quantum data)
 {
     this.data = data;
 }
 /// <summary>
 /// Costruttore statico per il setup iniziale
 /// </summary>
 public static Azione SetupPartita(Quantum quantum, Nave nave)
 {
     return new AzionePiazzaNave(quantum, nave) { obbligatoria = true, consumaAzione = false };
 }
Exemple #44
0
        public static void TestMultiSymbolGraph(this AbstractMultiSymbolIndicator ind, string[] filename, int length)
        {
            List <Quantum> lq = new List <Quantum>();

            foreach (string s in filename)
            {
                lq.Add(Quantum.ExcelToQuantum(s, s, 0));
            }
            MultiQuantum multiQuantum = MultiQuantum.OrganizeMultiQuantum(lq);


            var           dz    = new DenseMatrix(4 + 1 + ind.SubIndicatorSize, multiQuantum.Length);
            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 (List <Tick> t in multiQuantum)
            {
                dz[0, counter] = t[0].BidOpen;
                dz[1, counter] = t[0].BidHigh;
                dz[2, counter] = t[0].BidLow;
                dz[3, counter] = t[0].BidClose;

                dz[4, counter] = ind.HandleNextTicks(t.ToArray());

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

                counter++;
            }


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

            Console.WriteLine("Done Generating Graph for " + ind.ToString());
        }
Exemple #45
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");
            }
        }
Exemple #46
0
 /// <summary>
 /// Updates the color value in an inherited class.
 /// </summary>
 protected override void UpdateColor()
 {
     Color.R = Quantum.ScaleToQuantum(Y - (3.945707070708279e-05 * (U - 0.5)) + (1.1398279671717170825 * (V - 0.5)));
     Color.G = Quantum.ScaleToQuantum(Y - (0.3946101641414141437 * (U - 0.5)) - (0.5805003156565656797 * (V - 0.5)));
     Color.B = Quantum.ScaleToQuantum(Y + (2.0319996843434342537 * (U - 0.5)) - (4.813762626262513e-04 * (V - 0.5)));
 }
Exemple #47
0
 public MarketDataEventArg(Quantum data)
 {
     this.data = data;
 }