Exemplo n.º 1
0
 protected override bool Process(MarketData indicator, DateTime updateTime, Price value, ref Signal.Tick tradingOrder)
 {
     KeyValuePair<DateTime, Price>? timeValueLow = _low.TimeSeries[updateTime];
     KeyValuePair<DateTime, Price>? timeValueHigh = _high.TimeSeries[updateTime];
     if (timeValueLow == null || timeValueHigh == null)
         return false;
     if (_high.TimeSeries.TotalMinutes(updateTime) < _high.Period / 60)
         return false;
     Price lowWMA = timeValueLow.Value.Value;
     Price highWMA = timeValueHigh.Value.Value;
     var signalValue = lowWMA - highWMA;
     SIGNAL_CODE oldSignalCode = _signalCode;
     if (signalValue.Offer > 0)
     {
         tradingOrder = _onBuy;
         _signalCode = SIGNAL_CODE.BUY;
     }
     else if (signalValue.Bid < 0)
     {
         tradingOrder = _onSell;
         _signalCode = SIGNAL_CODE.SELL;
     }
     else
         return false;
     return oldSignalCode != SIGNAL_CODE.UNKNOWN && oldSignalCode != SIGNAL_CODE.HOLD && oldSignalCode != _signalCode;
 }
Exemplo n.º 2
0
 public SignalANN(MarketData asset, string annid, int version, List<Indicator> indicators, List<decimal> weights)
     : base("ANN_" + annid + "_" + version.ToString() + "_" + asset.Id, asset)
 {
     string[] anncomponents = annid.Split('_');
     _ann = new NeuralNetwork(int.Parse(anncomponents[1]), 1, anncomponents[2].Split('#').Select(str => int.Parse(str)).ToList(), weights);
     _mktIndicator = indicators;
     _indicatorLatestValues = new Dictionary<string,KeyValuePair<DateTime,Price>>();
     _inputValues = new List<double>();
 }
Exemplo n.º 3
0
 public ModelANN(string annid, ModelMacD macD, List<MarketData> daxStocks, MarketData vix, List<MarketData> otherIndices)
 {
     _annId = annid;
     _macD = macD;
     _index = macD.Index;
     _daxStocks = daxStocks;
     _otherIndices = otherIndices;
     _vix = vix;
     if (_vix != null)
         _mktIndices.Add(_vix);
 }
Exemplo n.º 4
0
 public ModelMacD(MarketData index, int lowPeriod = 2, int midPeriod = 10, int highPeriod = 60, MarketData tradingIndex = null)
 {
     if (Config.Settings.ContainsKey("ASSUMPTION_TREND"))
         _trendAssumption = Config.Settings["ASSUMPTION_TREND"] == "BULL" ? SIGNAL_CODE.BUY : SIGNAL_CODE.SELL;
     List<MarketData> mktData = new List<MarketData>();
     mktData.Add(index);
     _mktData = mktData;
     _index = index;
     _tradingIndex = tradingIndex == null ? index : tradingIndex;
     _lowPeriod = lowPeriod;
     _midPeriod = midPeriod;
     _highPeriod = highPeriod;
 }
Exemplo n.º 5
0
 protected override void OnUpdate(MarketData mktData, DateTime updateTime, Price value)
 {
     if (mktData.TimeSeries.TotalMinutes(updateTime) > _interval.TotalMinutes)
     {
         decimal? coeff = linearCoeff(updateTime);
         if (coeff != null)
         {
             Price price = new Price(coeff.Value);
             base.OnUpdate(mktData, updateTime, price);
             Publish(updateTime, price);
         }
     }
 }
Exemplo n.º 6
0
Arquivo: ANN.cs Projeto: JBetser/MiDax
 public static void Run(List<DateTime> dates, bool generate = false, bool generate_from_db = false, bool publish_to_db = false, bool use_uat_db = false, bool fullday = false)
 {
     TestEngine testEngine = new TestEngine("ANN", dates, generate, generate_from_db, publish_to_db, use_uat_db, fullday);
     testEngine.Settings["TRADING_SIGNAL"] = "ANN_FX_5_2_1_IX.D.DAX.DAILY.IP";
     testEngine.Settings["TIME_GMT"] = "-4";
     var models = new List<Model>();
     var index = new MarketData("EURUSD:CS.D.EURUSD.TODAY.IP");
     models.Add(new ModelMacDTest(index, 10, 30, 90));
     List<MarketData> otherIndices = new List<MarketData>();
     otherIndices.Add(index);
     models.Add(new ModelANN("FX_6_2", (ModelMacD)models[0], null, null, otherIndices));
     testEngine.Run(models);
 }
Exemplo n.º 7
0
 public SignalMacD(MarketData asset, int lowPeriod, int highPeriod, IndicatorEMA low = null, IndicatorEMA high = null, MarketData tradingAsset = null)
     : base("MacD_" + lowPeriod + "_" + highPeriod + "_" + asset.Id, asset, tradingAsset)
 {
     if (Config.Settings.ContainsKey("ASSUMPTION_TREND"))
         _trendAssumption = Config.Settings["ASSUMPTION_TREND"] == "BULL" ? SIGNAL_CODE.BUY : SIGNAL_CODE.SELL;
     _low = low == null ? new IndicatorEMA(asset, lowPeriod) : new IndicatorEMA(low);
     if (low != null)
         _low.PublishingEnabled = false;
     _high = high == null ? new IndicatorEMA(asset, highPeriod) : new IndicatorEMA(high);
     if (high != null)
         _high.PublishingEnabled = false;
     _mktIndicator.Add(_low);
     _mktIndicator.Add(_high);
 }
Exemplo n.º 8
0
        public static void Run(List<DateTime> dates, bool generate = false, bool generate_from_db = false, bool publish_to_db = false, bool use_uat_db = false, bool fullday = false)
        {
            TestEngine testEngine = new TestEngine("heuristic", dates, generate, generate_from_db, publish_to_db, use_uat_db, fullday);
            testEngine.Settings["TRADING_SIGNAL"] = "FXMole_1_14_CS.D.EURUSD.TODAY.IP,FXMole_1_14_CS.D.GBPUSD.TODAY.IP,FXMole_1_14_CS.D.USDJPY.TODAY.IP,FXMole_1_14_CS.D.AUDUSD.TODAY.IP";
            testEngine.Settings["TIME_GMT"] = "-4";
            testEngine.Settings["TIME_DECAY_FACTOR"] = "3";
            testEngine.Settings["ASSUMPTION_TREND"] = "BEAR";
            testEngine.Settings["INDEX_ICEDOW"] = "DOW:IceConnection.DJI";
            testEngine.Settings["INDEX_DOW"] = "DOW:IX.D.DOW.DAILY.IP";
            testEngine.Settings["INDEX_DAX"] = "DAX:IX.D.DAX.DAILY.IP";
            testEngine.Settings["INDEX_CAC"] = "CAC:IX.D.CAC.DAILY.IP";
            testEngine.Settings["FX_GBPUSD"] = "GBPUSD:CS.D.GBPUSD.TODAY.IP";
            testEngine.Settings["FX_EURUSD"] = "EURUSD:CS.D.EURUSD.TODAY.IP";
            testEngine.Settings["FX_USDJPY"] = "USDJPY:CS.D.USDJPY.TODAY.IP";
            testEngine.Settings["FX_AUDUSD"] = "AUDUSD:CS.D.AUDUSD.TODAY.IP";

            //List<string> rsiRefMappingJPYGBP = new List<string> { testEngine.Settings["FX_GBPEUR"], testEngine.Settings["FX_USDJPY"] };
            //List<string> rsiRefMappingUSD = new List<string> { testEngine.Settings["FX_GBPUSD"], testEngine.Settings["FX_EURUSD"] };
            //List<decimal> volcoeffsJPYGBP = new List<decimal> { 0.7m, 0.8m };
            //List<decimal> volcoeffsUSD = new List<decimal> { 0.75m, 1.0m, 0.8m };

            var index = IceStreamingMarketData.Instance;
            var gbpusd = new MarketData(testEngine.Settings["FX_GBPUSD"]);
            var eurusd = new MarketData(testEngine.Settings["FX_EURUSD"]);
            var usdjpy = new MarketData(testEngine.Settings["FX_USDJPY"]);
            var audusd = new MarketData(testEngine.Settings["FX_AUDUSD"]);
            var models = new List<Model>();
            var macD_10_30_90_gbpusd = new ModelMacD(gbpusd, 10, 30, 90);
            var macD_10_30_90_eurusd = new ModelMacD(eurusd, 10, 30, 90);
            var macD_10_30_90_usdjpy = new ModelMacD(usdjpy, 10, 30, 90);
            var macD_10_30_90_audusd = new ModelMacD(audusd, 10, 30, 90);
            decimal volcoeffEURUSD = 0.7m;
            decimal volcoeffGBPUSD = 0.85m;
            decimal volcoeffUSDJPY = 0.65m;
            decimal volcoeffAUDUSD = 0.6m;
            var fxmole_eurusd = new ModelFXMole(new List<MarketData> { eurusd, gbpusd }, macD_10_30_90_eurusd, volcoeffEURUSD);
            var fxmole_gbpusd = new ModelFXMole(new List<MarketData> { gbpusd, eurusd }, macD_10_30_90_gbpusd, volcoeffGBPUSD);
            var fxmole_usdjpy = new ModelFXMole(new List<MarketData> { usdjpy, eurusd }, macD_10_30_90_usdjpy, volcoeffUSDJPY);
            var fxmole_audusd = new ModelFXMole(new List<MarketData> { audusd, eurusd }, macD_10_30_90_audusd, volcoeffAUDUSD);
            models.Add(macD_10_30_90_gbpusd);
            models.Add(macD_10_30_90_eurusd);
            models.Add(macD_10_30_90_usdjpy);
            models.Add(macD_10_30_90_audusd);
            models.Add(fxmole_gbpusd);
            models.Add(fxmole_eurusd);
            models.Add(fxmole_usdjpy);
            models.Add(fxmole_audusd);
            testEngine.Run(models);
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            DateTime start = DateTime.Parse(args[0]);
            DateTime end = DateTime.Parse(args[1]);

            Dictionary<string, string> dicSettings = new Dictionary<string, string>();
            dicSettings["APP_NAME"] = "Midax";
            dicSettings["TIMESERIES_MAX_RECORD_TIME_HOURS"] = "12";
            dicSettings["LIMIT"] = "10";
            dicSettings["REPLAY_MODE"] = "DB";
            dicSettings["DB_CONTACTPOINT"] = "192.168.1.25";
            dicSettings["REPLAY_POPUP"] = "1";
            dicSettings["TRADING_MODE"] = "SELECT";
            dicSettings["CALENDAR_PATH"] = @"C:\Shared\MidaxTester\Calendar";
            dicSettings["TIME_GMT"] = "-4";
            Config.Settings = dicSettings;

            while (start <= end)
            {
                //List<string> mktdataFiles = new List<string>();
                //mktdataFiles.Add(string.Format("..\\..\\..\\..\\DBImporter\\MktData\\mktdata_{0}_{1}_{2}.csv", start.Day, start.Month, start.Year));
                //Config.Settings["REPLAY_CSV"] = Config.TestList(mktdataFiles);
                Config.Settings["PUBLISHING_START_TIME"] = string.Format("{0}-{1}-{2} {3}:{4}:{5}", start.Year, start.Month, start.Day, 6, 25, 0);
                Config.Settings["PUBLISHING_STOP_TIME"] = string.Format("{0}-{1}-{2} {3}:{4}:{5}", start.Year, start.Month, start.Day, 18, 0, 0);
                Config.Settings["TRADING_START_TIME"] = string.Format("{0}-{1}-{2} {3}:{4}:{5}", start.Year, start.Month, start.Day, 8, 0, 0);
                Config.Settings["TRADING_STOP_TIME"] = string.Format("{0}-{1}-{2} {3}:{4}:{5}", start.Year, start.Month, start.Day, 17, 0, 0);
                Config.Settings["TRADING_CLOSING_TIME"] = string.Format("{0}-{1}-{2} {3}:{4}:{5}", start.Year, start.Month, start.Day, 16, 55, 0);
                Config.Settings["PUBLISHING_CSV"] = string.Format("..\\..\\..\\MktSelectorData\\mktselectdata_{0}_{1}_{2}.csv", start.Day, start.Month, start.Year);

                MarketDataConnection.Instance.Connect(null);
                MarketData index = new MarketData("EURUSD:CS.D.EURUSD.TODAY.IP");
                index.Subscribe(OnUpdateMktData,null);
                MarketDataConnection.Instance.StartListening();
                MarketDataConnection.Instance.StopListening();
                index.Unsubscribe(OnUpdateMktData,null);
                index.Clear();

                do
                {
                    start = start.AddDays(1);
                }
                while (start.DayOfWeek == DayOfWeek.Saturday || start.DayOfWeek == DayOfWeek.Sunday);
            }
        }
Exemplo n.º 10
0
        protected override bool Process(MarketData indicator, DateTime updateTime, Price value, ref Signal.Tick tradingOrder)
        {
            if (indicator.TimeSeries.Count == 0)
                return false;
            _indicatorLatestValues[indicator.Id] = new KeyValuePair<DateTime, Price>(updateTime, indicator.TimeSeries.Last());

            DateTime dt = DateTime.MinValue;
            foreach (var ind in _indicatorLatestValues)
            {
                if (dt == DateTime.MinValue)
                {
                    dt = ind.Value.Key;
                    continue;
                }
                if (dt != ind.Value.Key)
                    return false;
            }

            _inputValues.Clear();
            if (!ComputeOutput())
                return false;

            _ann.CalculateOutput(_inputValues);
            var output = _ann.GetOutput()[0];

            if (output > 0.5 && _signalCode != SIGNAL_CODE.BUY)
            {
                tradingOrder = _onBuy;
                _signalCode = SIGNAL_CODE.BUY;
            }
            else if (output < -0.5 && _signalCode != SIGNAL_CODE.SELL)
            {
                tradingOrder = _onSell;
                _signalCode = SIGNAL_CODE.SELL;
            }
            else{
                tradingOrder = _onHold;
                _signalCode = SIGNAL_CODE.HOLD;
            }
            return true;
        }
Exemplo n.º 11
0
        static void GET(string symbol)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("{0}?symbol={1}", DATA_SRC, symbol));
                request.Method = "GET";

                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        var responseData = reader.ReadToEnd();
                        var dict = js.Deserialize<dynamic>(responseData.Substring(18, responseData.Length - 19));

                        var marketData = new MarketData(symbol);
                        var dateComponents = dict["Timestamp"].Split(' ');
                        var timeComponents = dateComponents[3].Split(':');
                        var month = DateTime.ParseExact(dateComponents[1], "MMM", CultureInfo.CurrentCulture).Month;
                        var updateTime = new DateTime(int.Parse(dateComponents[5]), month, int.Parse(dateComponents[2]), int.Parse(timeComponents[0]), int.Parse(timeComponents[1]), int.Parse(timeComponents[2]), DateTimeKind.Utc);
                        var hourOffset = int.Parse(dateComponents[4].Split('-')[1].Split(':')[0]);
                        updateTime = updateTime.AddHours(hourOffset);
                        if (!stockPriceCache.ContainsKey(symbol))
                            stockPriceCache[symbol] = new KeyValuePair<DateTime, decimal>(DateTime.MinValue, 0m);
                        if (stockPriceCache[symbol].Key != updateTime && stockPriceCache[symbol].Value != (decimal)dict["LastPrice"])
                        {
                            stockPriceCache[symbol] = new KeyValuePair<DateTime, decimal>(updateTime, dict["LastPrice"]);
                            var stockPrice = new Price(dict["LastPrice"]);
                            stockPrice.Volume = dict["Volume"];
                            CassandraConnection.Instance.Insert(updateTime, marketData, stockPrice);
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                if (ex.Status != WebExceptionStatus.ProtocolError)
                    Log.Instance.WriteEntry(ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
        }
Exemplo n.º 12
0
        protected override void OnUpdate(MarketData mktData, DateTime updateTime, Price value)
        {
            DateTime startTime;
            if (_curAvg == null)
            {
                startTime = updateTime.AddSeconds(-_periodSeconds);
                if (MarketData.TimeSeries.Count == 0)
                    return;
                if (MarketData.TimeSeries.StartTime() > startTime)
                    return;
                _decrementStartTime = startTime;
                var curAvg = new Price();
                MobileVolume(ref curAvg, startTime, updateTime);
                if (curAvg == null)
                    return;
                _curAvg = curAvg;
            }
            else
            {
                startTime = _curAvgTime;
                var decrementUpdateTime = updateTime.AddSeconds(-_periodSeconds);

                var decrementAvg = new Price(0m,0m,0m);
                MobileVolume(ref decrementAvg, _decrementStartTime, decrementUpdateTime);
                decrementAvg.Bid = decrementAvg.Volume.Value;
                decrementAvg.Offer = decrementAvg.Volume.Value;
                _curAvg = _curAvg - decrementAvg + Math.Abs(value.Volume.Value) / (decimal)_periodSeconds;

                _curAvg.Volume = _curAvg.Bid;
                _decrementStartTime = decrementUpdateTime;
            }

            _curAvg.Bid = _curAvg.Volume.Value;
            _curAvg.Offer = _curAvg.Volume.Value;
            _curAvgTime = updateTime;
            Publish(updateTime, _curAvg.Volume.Value);
        }
Exemplo n.º 13
0
 static void OnUpdate(MarketData mktData, DateTime updateTime, Price value)
 {
 }
Exemplo n.º 14
0
        protected override bool Process(MarketData indicator, DateTime updateTime, Price value, ref Signal.Tick tradingOrder)
        {
            if (_calendar == null)
            {
                _calendar = new Calendar(updateTime);
            }
            IndicatorRSI rsi = (IndicatorRSI)indicator;

            if (indicator.TimeSeries.TotalMinutes(updateTime) < _timeFrameMn)
            {
                return(false);
            }
            if (!_startValue.HasValue)
            {
                _startValue = value.Mid();
            }
            Price curRsi  = rsi.TimeSeries.Last();
            Price prevRsi = rsi.TimeSeries.PrevValue(updateTime).Value.Value;

            if ((prevRsi.Bid <= 50m && curRsi.Bid >= 50m) || (curRsi.Bid <= 50m && prevRsi.Bid >= 50m))
            {
                _rsi_loss_reset = true;
            }
            //_rsiSellThreshold += Math.Max(0m, curRsi.Bid - (decimal)getSellThreshold()) / 2m;
            //_rsiBuyThreshold += Math.Min(0m, curRsi.Bid - (decimal)getBuyThreshold()) / 2m;
            var minVal = _asset.TimeSeries.Min(updateTime.AddMinutes(-_timeFrameStopLossMn), updateTime);
            var maxVal = _asset.TimeSeries.Max(updateTime.AddMinutes(-_timeFrameStopLossMn), updateTime);

            if (maxVal - minVal > _maxVol)
            {
                //WriteBlockReason(updateTime, string.Format("reset due to vol > {0}", _maxVol));
                _rsi_loss_reset = false;
            }
            minVal = _asset.TimeSeries.Min(updateTime.AddMinutes(-_timeFrameBottomMn), updateTime);
            maxVal = _asset.TimeSeries.Max(updateTime.AddMinutes(-_timeFrameBottomMn), updateTime);
            if (maxVal - minVal > _maxLongVol)
            {
                //WriteBlockReason(updateTime, string.Format("reset due to long vol > {0}", _maxLongVol));
                _rsi_loss_reset = false;
            }
            if (Math.Abs(value.Mid() - _startValue.Value) > _maxTotalVol)
            {
                WriteBlockReason(updateTime, string.Format("stopped trading due to vol > {0}", _maxTotalVol));
                _stopTrading = true;
            }
            if (_tradingStart > DateTime.MinValue)
            {
                if ((decimal)(updateTime - _tradingStart).TotalMilliseconds > _timeFrameStopLossMn * 60000m)
                {
                    _rsi_loss_reset = false;
                    return(close(_id + string.Format(" close event due to timeout, AssetStart = {0}, Value = {1}", _tradingStartValue, value.Bid), ref tradingOrder));
                }
                else
                {
                    int     idxStopLoss = -1;
                    decimal ratio       = 0m;
                    foreach (var interval in stopLossTimes)
                    {
                        idxStopLoss++;
                        if (interval.IsInside((int)(updateTime - _tradingStart).TotalMinutes))
                        {
                            ratio = interval.Ratio((decimal)(updateTime - _tradingStart).TotalMinutes);
                            break;
                        }
                    }
                    if (_signalCode == SIGNAL_CODE.BUY)
                    {
                        var assetMin    = rsi.MinAsset((int)(updateTime - _tradingStart).TotalMinutes + 1);
                        var stopWin     = stopWinValues[idxStopLoss].Value(ratio);
                        var stopBigLoss = bigStopLossValues[idxStopLoss].Value(ratio);
                        if (value.Bid >= _tradingStartValue + stopWin && curRsi.Bid >= getBuyThreshold() + 10)
                        {
                            return(close(_id + string.Format(" close event due to stop win. SELL AssetStart = {0}, LastValue = {1}, StopWin = {2}", _tradingStartValue, value.Bid, stopWin), ref tradingOrder));
                        }
                        else if (value.Bid - assetMin >= stopWin && curRsi.Bid >= getBuyThreshold() + 10)
                        {
                            if (value.Bid > _tradingStartValue)
                            {
                                return(close(_id + string.Format(" close event due to stop win. SELL AssetStart = {0}, LastValue = {1}", _tradingStartValue, value.Bid), ref tradingOrder));
                            }
                            else
                            {
                                _rsi_loss_reset = false;
                                return(close(_id + string.Format(" close event due to stop loss. SELL AssetStart = {0}, LastValue = {1}", _tradingStartValue, value.Bid), ref tradingOrder));
                            }
                        }
                        else if (value.Bid - _tradingStartValue >= stopBigLoss)
                        {
                            _rsi_loss_reset = false;
                            return(close(_id + string.Format(" close event due to stop loss. SELL AssetMin = {0}, LastValue = {1}, StopLoss = {2}", assetMin, value.Bid, stopBigLoss), ref tradingOrder));
                        }/*
                          * else if (_trend.TimeSeries.Last().Bid <= _tradingTrend - 5m && curRsi.Bid >= getBuyThreshold() + 10)
                          * {
                          * if (value.Offer > _tradingStartValue)
                          *     return close(_id + string.Format(" close event due to stop win forced by trend. SELL AssetStart = {0}, LastValue = {1}", _tradingStartValue, value.Offer), ref tradingOrder);
                          * else
                          * {
                          *     _rsi_loss_reset = false;
                          *     return close(_id + string.Format(" close event due to stop loss forced by trend. SELL AssetStart = {0}, LastValue = {1}", _tradingStartValue, value.Offer), ref tradingOrder);
                          * }
                          * }*/
                        else
                        {
                            var stopLoss    = stopLossValues[idxStopLoss].Value(ratio);
                            var bigStopLoss = bigStopLossValues[idxStopLoss].Value(ratio);
                            if ((_tradingStartValue - value.Bid >= stopLoss && curRsi.Bid >= getBuyThreshold() + 20) ||
                                (_tradingStartValue - value.Bid >= bigStopLoss))
                            {
                                _rsi_loss_reset = false;
                                return(close(_id + string.Format(" close event due to stop loss. SELL AssetStart = {0}, LastValue = {1}, StopLoss = {2}", _tradingStartValue, value.Bid, stopLoss), ref tradingOrder));
                            }
                        }
                    }
                    else
                    {
                        var assetMax    = rsi.MaxAsset((int)(updateTime - _tradingStart).TotalMinutes + 1);
                        var stopWin     = stopWinValues[idxStopLoss].Value(ratio);
                        var stopBigLoss = bigStopLossValues[idxStopLoss].Value(ratio);
                        if (value.Offer <= _tradingStartValue - stopWin && curRsi.Bid <= getSellThreshold() - 10)
                        {
                            return(close(_id + string.Format(" close event due to stop win. BUY AssetStart = {0}, LastValue = {1}, StopWin = {2}", _tradingStartValue, value.Offer, stopWin), ref tradingOrder));
                        }
                        else if (assetMax - value.Offer >= stopWin && curRsi.Bid <= getSellThreshold() - 10)
                        {
                            if (value.Offer < _tradingStartValue)
                            {
                                return(close(_id + string.Format(" close event due to stop win. BUY AssetStart = {0}, LastValue = {1}", _tradingStartValue, value.Offer), ref tradingOrder));
                            }
                            else
                            {
                                _rsi_loss_reset = false;
                                return(close(_id + string.Format(" close event due to stop loss. BUY AssetStart = {0}, LastValue = {1}", _tradingStartValue, value.Offer), ref tradingOrder));
                            }
                        }
                        else if (assetMax - value.Offer >= stopBigLoss)
                        {
                            _rsi_loss_reset = false;
                            return(close(_id + string.Format(" close event due to stop loss. BUY AssetMax = {0}, LastValue = {1}, StopLoss = {2}", assetMax, value.Offer, stopBigLoss), ref tradingOrder));
                        }/*
                          * else if (_trend.TimeSeries.Last().Bid >= _tradingTrend + 5m && curRsi.Bid <= getSellThreshold() - 10)
                          * {
                          * if (value.Offer < _tradingStartValue)
                          *     return close(_id + string.Format(" close event due to stop win forced by trend. BUY AssetStart = {0}, LastValue = {1}", _tradingStartValue, value.Offer), ref tradingOrder);
                          * else
                          * {
                          *     _rsi_loss_reset = false;
                          *     return close(_id + string.Format(" close event due to stop loss forced by trend. BUY AssetStart = {0}, LastValue = {1}", _tradingStartValue, value.Offer), ref tradingOrder);
                          * }
                          * }*/
                        else
                        {
                            var stopLoss    = stopLossValues[idxStopLoss].Value(ratio);
                            var bigStopLoss = bigStopLossValues[idxStopLoss].Value(ratio);
                            if ((value.Offer - _tradingStartValue >= stopLoss && curRsi.Bid <= getSellThreshold() - 20) ||
                                (value.Offer - _tradingStartValue >= bigStopLoss))
                            {
                                _rsi_loss_reset = false;
                                return(close(_id + string.Format(" close event due to stop loss. BUY AssetStart = {0}, LastValue = {1}, StopLoss = {2}", _tradingStartValue, value.Offer, stopLoss), ref tradingOrder));
                            }
                        }
                    }
                }
            }
            else
            {
                if (!_rsi_loss_reset || _stopTrading || maxVal - minVal < _minVol || value.Offer - value.Bid > _maxSpread)
                {
                    return(false);
                }

                /*
                 * foreach (var rsiRef in _rsiRefs)
                 * {
                 *  if (rsiRef.TimeSeries.Count > 0)
                 *  {
                 *      if (Math.Abs(curRsi.Mid() - 50m) < Math.Abs(rsiRef.TimeSeries.Last().Mid() - 50m))
                 *          return false;
                 *  }
                 * }*/
                string eventName = "";
                if (_calendar.IsNearEvent(_asset.Name, updateTime, ref eventName))
                {
                    WriteBlockReason(updateTime, "deal blocked by event: " + eventName);
                    _rsi_loss_reset = false;
                    return(false);
                }
                var rsiMax = rsi.MaxRsi(_timeFramePeakMn);
                var rsiMin = rsi.MinRsi(_timeFramePeakMn);
                //var rsiLongMax = _rsiLong.MaxRsi(_timeFrameRsiLongMn);
                //var rsiLongMin = _rsiLong.MinRsi(_timeFrameRsiLongMn);
                var rsiAdjustment   = Math.Max(0, rsi.MaxRsi(_timeFrameBottomMn) - getSellThreshold()) - Math.Max(0, getBuyThreshold() - rsi.MinRsi(_timeFrameBottomMn));
                var curEmaVeryShort = _emaVeryShort.TimeSeries.Last();
                var curEmaShort     = _emaShort.TimeSeries.Last();
                var curEmaLong      = _emaLong.TimeSeries.Last();
                var curVol          = _wmvol.TimeSeries.Last().Bid;
                if (curVol < _maxWmVol)
                {
                    WriteBlockReason(updateTime, "deal blocked due to vol < " + _maxWmVol);
                    return(false);
                }
                var curVolAvg = (_wmvol.Min() + _wmvol.Max()) / 2m;
                if (curVol < curVolAvg)
                {
                    WriteBlockReason(updateTime, "deal blocked due to vol < vol average");
                    return(false);
                }
                if ((curRsi.Bid >= getSellThreshold()) &&
                    //(curRsi.Bid - rsiAdjustment >= getSellThreshold() && curRsi.Bid >= (getSellThreshold() - 10))) && (rsiLongMax >= getSellThreshold() - 15m) &&
                    (curRsi.Bid > rsiMax - _startThreshold) && (curEmaVeryShort.Mid() + _maxShortMacDSpread > curEmaLong.Mid()) &&
                    (Math.Abs(curEmaShort.Mid() - curEmaLong.Mid()) < _maxLongMacDSpread))
                {
                    var curVolTrend = _volTrend.TimeSeries.Last().Bid;
                    if (curVolTrend > 0.5m || curVolTrend < 0m)
                    {
                        WriteBlockReason(updateTime, "deal blocked due to vol not within 0 < trend < 0.5");
                        return(false);
                    }
                    if (!_volTrendTrend.IsMin(2, curVolTrend, 0.01m) || _volTrendTrend.IsMax(2, curVolTrend, 0.02m))
                    {
                        WriteBlockReason(updateTime, "sell event blocked due to vol trend not 1mn minimum");
                        return(false);
                    }
                    tradingOrder       = _onSell;
                    _signalCode        = SIGNAL_CODE.SELL;
                    _tradingStart      = updateTime;
                    _tradingStartValue = value.Bid;
                    _tradingTrend      = _trend.TimeSeries.Last().Bid;
                    if (curRsi.Bid >= getSellThreshold())
                    {
                        Log.Instance.WriteEntry(_id + " sell event due to RSI >= getSellThreshold()");
                    }
                    //                    else if (Math.Abs(curRsi.Bid - rsiMax) < _startThreshold)
                    //                      Log.Instance.WriteEntry(_id + " sell event due highest RSI peak reached");
                    else
                    {
                        Log.Instance.WriteEntry(_id + " sell event due to adjusted RSI >= getSellThreshold()");
                    }
                    return(true);
                }
                else if ((curRsi.Bid <= getBuyThreshold()) &&
                         //(curRsi.Bid + rsiAdjustment <= getBuyThreshold() && curRsi.Bid <= (getBuyThreshold() + 10))) && (rsiLongMin <= getBuyThreshold() + 15m) &&
                         (curRsi.Bid < rsiMin + _startThreshold) && (curEmaVeryShort.Mid() - _maxShortMacDSpread < curEmaLong.Mid()) &&
                         (Math.Abs(curEmaShort.Mid() - curEmaLong.Mid()) < _maxLongMacDSpread))
                {
                    var curVolTrend = _volTrend.TimeSeries.Last().Bid;
                    if (curVolTrend < -0.5m || curVolTrend > 0m)
                    {
                        WriteBlockReason(updateTime, "deal blocked due to vol not within -0.5 < trend < 0");
                        return(false);
                    }
                    if (!_volTrendTrend.IsMax(2, curVolTrend, 0.01m) || _volTrendTrend.IsMin(2, curVolTrend, 0.02m))
                    {
                        WriteBlockReason(updateTime, "buy event blocked due to vol trend not 1mn maximum");
                        return(false);
                    }
                    tradingOrder       = _onBuy;
                    _signalCode        = SIGNAL_CODE.BUY;
                    _tradingStart      = updateTime;
                    _tradingStartValue = value.Offer;
                    _tradingTrend      = _trend.TimeSeries.Last().Bid;
                    if (curRsi.Bid <= getBuyThreshold())
                    {
                        Log.Instance.WriteEntry(_id + " buy event due to RSI <= getBuyThreshold()");
                    }
                    //                   else if (Math.Abs(curRsi.Bid - rsiMin) < _startThreshold)
                    //                     Log.Instance.WriteEntry(_id + " buy event due lowest RSI peak reached");
                    else
                    {
                        Log.Instance.WriteEntry(_id + " buy event due to adjusted RSI <= getBuyThreshold()");
                    }
                    return(true);
                }
                else
                {
                    _signalCode        = SIGNAL_CODE.HOLD;
                    _tradingStart      = DateTime.MinValue;
                    _tradingStartValue = 0m;
                }
            }
            return(false);
        }
Exemplo n.º 15
0
 public SignalANNWMA_5_2(MarketData asset, List <Indicator> indicators, List <decimal> weights)
     : base(asset, "WMA_5_2", 1, indicators, weights)
 {
 }
Exemplo n.º 16
0
 public IndicatorVEMA(MarketData mktData, int periodMinutes, IndicatorVolume cumVol = null)
     : base("VEMA_" + periodMinutes + "_" + mktData.Id, mktData, periodMinutes)
 {
     _cumVolume = cumVol == null ? new IndicatorVolume(mktData, periodMinutes) : cumVol;
 }
Exemplo n.º 17
0
        protected override Price IndicatorFunc(MarketData mktData, DateTime updateTime, Price value)
        {
            if (_wma.TimeSeries.Count == 0 || _wmaRef.TimeSeries.Count == 0)
            {
                return(null);
            }
            if (updateTime > _nextCorrelTime)
            {
                _nextCorrelTime = (_nextCorrelTime == DateTime.MinValue ? updateTime : _nextCorrelTime).AddSeconds(_periodSeconds);
            }
            var   curCorrel      = 0m;
            var   curValue       = 0m;
            var   curVar         = 0.0;
            var   curVarRef      = 0.0;
            Price priceCurCorrel = null;

            if (_prevCorrel.HasValue)
            {
                if (_wma.TimeSeries.StartTime() > _startTime)
                {
                    return(null);
                }
                if (_wmaRef.TimeSeries.StartTime() > _startTime)
                {
                    return(null);
                }
                if (_wmaRef.TimeSeries.EndTime() != _wma.TimeSeries.EndTime())
                {
                    return(null);
                }
                var curPeriod = (decimal)(updateTime - _startTime).TotalMilliseconds;
                if (curPeriod > _periodMilliSeconds)
                {
                    curPeriod = _periodMilliSeconds;
                }
                var timeDecay      = _timeDecayWeight * (decimal)(updateTime - _startTime).TotalSeconds;
                var k              = (curPeriod + timeDecay) / _periodMilliSeconds;
                var avg            = _wma.TimeSeries.Last();
                var avgRef         = _wmaRef.TimeSeries.Last();
                var curVarValue    = Math.Pow((double)(value.Bid - avg.Bid), 2);
                var curVarRefValue = Math.Pow((double)(_wmaRef.SignalStock.TimeSeries.Last().Bid - avgRef.Bid), 2);
                curVar    = (double)(_curVarValue.Bid * k) + _prevVar.Value * (1.0 - (double)k);
                curVarRef = (double)(_curVarRefValue.Bid * k) + _prevVarRef.Value * (1.0 - (double)k);
                if (curVar * curVarRef == 0)
                {
                    if (Math.Abs(curVarValue * curVarRefValue - curVar * curVarRef) < 0.01)
                    {
                        curValue = 1m;
                    }
                    else
                    {
                        curValue = 0m;
                    }
                }
                else
                {
                    curValue = (decimal)(Math.Sqrt((curVarValue * curVarRefValue) / (curVar * curVarRef)));
                }
                curCorrel       = _curValue.Bid * k + _prevCorrel.Value * (1m - k);
                _curVarValue    = new Price((decimal)curVarValue);
                _curVarRefValue = new Price((decimal)curVarRefValue);
                priceCurCorrel  = new Price(curCorrel);
            }
            else
            {
                _curVarValue    = new Price(0m);
                _curVarRefValue = new Price(0m);
                curValue        = 0m;
                curCorrel       = 0m;
            }
            _curValue   = new Price(curValue);
            _prevCorrel = curCorrel;
            _prevVar    = curVar;
            _prevVarRef = curVarRef;
            _startTime  = updateTime;
            return(priceCurCorrel);
        }
Exemplo n.º 18
0
 protected abstract bool Process(MarketData indicator, DateTime updateTime, Price value, ref Signal.Tick tradingOrder);
Exemplo n.º 19
0
 protected override void OnUpdate(MarketData mktData, DateTime updateTime, Price value)
 {
     _closeBid = value.Bid;
 }
Exemplo n.º 20
0
 public IndicatorCloseBid(MarketData mktData)
     : base(mktData, "CloseBid")
 {
 }
Exemplo n.º 21
0
 protected override bool Process(MarketData indicator, DateTime updateTime, Price value, ref Signal.Tick tradingOrder)
 {
     if (base.Process(indicator, updateTime, value, ref tradingOrder))
     {
         if (_trendAssumption != SIGNAL_CODE.BUY && tradingOrder == _onSell)
         {
             if (_low.TimeSeries.Count >= 2)
             {
                 var lowVal = _low.TimeSeries[updateTime].Value.Value;
                 var prevValues = _low.TimeSeries.Values(updateTime, new TimeSpan(0, 1, 0), true);
                 if (prevValues != null)
                 {
                     if (prevValues.Count >= 2)
                     {
                         var prevVal = prevValues[prevValues.Count - 2].Value;
                         if (_cascading)
                         {
                             if (_localMinimum > lowVal.Bid)
                                 _localMinimum = lowVal.Bid;
                             if (_localMaximum < lowVal.Bid)
                                 _localMaximum = lowVal.Bid;
                             if (_buying)
                             {
                                 if (lowVal.Bid < _localMaximum - _threshold)
                                 {
                                     _pivot = _localMaximum;
                                     _localMinimum = _localMaximum;
                                     _buying = false;
                                 }
                                 else if (lowVal.Bid > _pivot + _threshold)
                                 {
                                     _signalCode = SIGNAL_CODE.BUY;
                                     tradingOrder = _onBuy;
                                 }
                             }
                             else
                             {
                                 if (lowVal.Bid > _localMinimum + _threshold)
                                 {
                                     _pivot = _localMinimum;
                                     _localMaximum = _localMinimum;
                                     _signalCode = SIGNAL_CODE.BUY;
                                     tradingOrder = _onBuy;
                                     _buying = true;
                                 }
                             }
                         }
                         else
                         {
                             _cascading = true;
                             _localMinimum = lowVal.Bid;
                             _localMaximum = lowVal.Bid;
                             _pivot = _localMaximum;
                             _buying = false;
                         }
                         return true;
                     }
                 }
             }
         }
         else if (_trendAssumption != SIGNAL_CODE.SELL && tradingOrder == _onBuy)
         {
             if (_low.TimeSeries.Count >= 2)
             {
                 var lowVal = _low.TimeSeries[updateTime].Value.Value;
                 var prevValues = _low.TimeSeries.Values(updateTime, new TimeSpan(0, 1, 0), true);
                 if (prevValues != null)
                 {
                     if (prevValues.Count >= 2)
                     {
                         var prevVal = prevValues[prevValues.Count - 2].Value;
                         if (_cascading)
                         {
                             if (_localMinimum > lowVal.Offer)
                                 _localMinimum = lowVal.Offer;
                             if (_localMaximum < lowVal.Offer)
                                 _localMaximum = lowVal.Offer;
                             if (_selling)
                             {
                                 if (lowVal.Offer > _localMinimum + _threshold)
                                 {
                                     _pivot = _localMinimum;
                                     _localMaximum = _localMinimum;
                                     _selling = false;
                                 }
                                 else if (lowVal.Offer < _pivot - _threshold)
                                 {
                                     _signalCode = SIGNAL_CODE.SELL;
                                     tradingOrder = _onSell;
                                 }
                             }
                             else
                             {
                                 if (lowVal.Offer < _localMaximum - _threshold)
                                 {
                                     _pivot = _localMaximum;
                                     _localMinimum = _localMaximum;
                                     _signalCode = SIGNAL_CODE.SELL;
                                     tradingOrder = _onSell;
                                     _selling = true;
                                 }
                             }
                         }
                         else
                         {
                             _cascading = true;
                             _localMinimum = lowVal.Offer;
                             _localMaximum = lowVal.Offer;
                             _pivot = _localMinimum;
                             _selling = false;
                         }
                         return true;
                     }
                 }
             }
         }
         _cascading = false;
         _buying = false;
         _selling = false;
         return true;
     }
     return false;
 }
Exemplo n.º 22
0
 public SignalMacDCascade(MarketData asset, int verylowPeriod, int lowPeriod, int highPeriod, decimal threshold, IndicatorEMA low = null, IndicatorEMA high = null, MarketData tradingIndex = null)
     : base("MacDCas_" + verylowPeriod + "_" + lowPeriod + "_" + highPeriod + "_" + (int)decimal.Round(threshold * 100.0m) + "_" + asset.Id, asset, lowPeriod, highPeriod, low, high, tradingIndex)
 {
     _threshold = threshold;
 }
Exemplo n.º 23
0
 public abstract void Insert(DateTime updateTime, MarketData mktData, Price price);
Exemplo n.º 24
0
 public IndicatorVEMA(string id, MarketData mktData, int periodMinutes, IndicatorVolume cumVol = null)
     : base(id, mktData, periodMinutes)
 {
     _cumVolume = cumVol == null ? new IndicatorVolume(mktData, periodMinutes) : cumVol;
 }
Exemplo n.º 25
0
 public SignalMacDCascade(MarketData asset, int verylowPeriod, int lowPeriod, int highPeriod, decimal threshold, IndicatorEMA low = null, IndicatorEMA high = null, MarketData tradingIndex = null)
     : base("MacDCas_" + verylowPeriod + "_" + lowPeriod + "_" + highPeriod + "_" + (int)decimal.Round(threshold * 100.0m) + "_" + asset.Id, asset, lowPeriod, highPeriod, low, high, tradingIndex)
 {
     _threshold = threshold;
 }
Exemplo n.º 26
0
 public IndicatorCloseOffer(MarketData mktData)
     : base(mktData, "CloseOffer")
 {
 }
Exemplo n.º 27
0
 public Signal(string id, MarketData asset, MarketData tradingAsset = null)
 {
     this._id = id;
     this._name = id;
     this._asset = asset;
     this._tradingAsset = tradingAsset == null ? asset : tradingAsset;
     this._mktIndicator = new List<Indicator>();
 }
Exemplo n.º 28
0
 protected override void OnUpdate(MarketData mktData, DateTime updateTime, Price value)
 {
     _closeOffer = value.Offer;
 }
Exemplo n.º 29
0
 protected override bool Process(MarketData indicator, DateTime updateTime, Price value, ref Signal.Tick tradingOrder)
 {
     if (_tradingOrder == _onSell)
     {
         tradingOrder = _onBuy;
         _tradingOrder = _onBuy;
         return true;
     }
     else
     {
         tradingOrder = _onSell;
         _tradingOrder = _onSell;
         return true;
     }
 }
Exemplo n.º 30
0
 public IndicatorLevelPivot(MarketData mktData)
     : base(mktData, "LVLPivot")
 {
 }
Exemplo n.º 31
0
 public SignalMacDV(MarketData asset, int lowPeriod, int highPeriod, IndicatorVEMA low = null, IndicatorVEMA high = null, MarketData tradingAsset = null)
     : base("MacDV_" + lowPeriod + "_" + highPeriod + "_" + asset.Id, asset, lowPeriod, highPeriod, low, high, tradingAsset)
 {
     _low = low == null ? new IndicatorVEMA(asset, lowPeriod) : new IndicatorVEMA(low);
     if (low != null)
     {
         _low.PublishingEnabled = false;
     }
     _high = high == null ? new IndicatorVEMA(asset, highPeriod) : new IndicatorVEMA(high);
     if (high != null)
     {
         _high.PublishingEnabled = false;
     }
     _mktIndicator = new List <Indicator>();
     _mktIndicator.Add(_low);
     _mktIndicator.Add(_high);
 }
Exemplo n.º 32
0
 protected override void OnUpdate(MarketData mktData, DateTime updateTime, Price value)
 {
 }
Exemplo n.º 33
0
 public ModelALaCon(MarketData fx)
 {
     _fx = fx;
 }
Exemplo n.º 34
0
 public IndicatorLevelR2(MarketData mktData)
     : base(mktData, "LVLR2")
 {
 }
Exemplo n.º 35
0
        /*
         * public override void Insert(MarketLevels mktDetails)
         * {
         *  // this a source market data, no need to compare
         * }*/

        public override void Insert(DateTime updateTime, MarketData mktData, Price price)
        {
            // this a source market data, no need to compare
        }
Exemplo n.º 36
0
 public IndicatorLevelS3(MarketData mktData)
     : base(mktData, "LVLS3")
 {
 }
Exemplo n.º 37
0
        static void Main(string[] args)
        {
            int curArg = 0;
            DateTime start = DateTime.MinValue;
            DateTime end = DateTime.MinValue;
            bool wholeMonth = false;
            if (args[0].Split('-').Length == 2)
            {
                var year = int.Parse(args[0].Split('-')[0]);
                var month =  int.Parse(args[0].Split('-')[1]);
                start = new DateTime(year, month, 1, 5, 45, 0);
                end = new DateTime(year, month, DateTime.DaysInMonth(year, month), 22, 0, 0);
                wholeMonth = true;
                curArg++;
            }
            else
            {
                start = DateTime.Parse(args[curArg++]);
                end = DateTime.Parse(args[curArg++]);
            }

            bool restoreDB = false;
            bool fromDB = true;
            bool deleteDB = false;
            if (args.Length > curArg)
            {
                restoreDB = (args[curArg++].ToUpper() == "-RESTOREDB");
                fromDB = false;
            }
            if (args.Length > curArg)
            {
                fromDB = (args[curArg].ToUpper() == "-FROMDB");
                deleteDB = (args[curArg].ToUpper() == "-DELETEDB");
            }
            Dictionary<string, string> dicSettings = new Dictionary<string, string>();
            dicSettings["APP_NAME"] = "Midax";
            dicSettings["DB_CONTACTPOINT"] = "192.168.1.25";
            dicSettings["REPLAY_MODE"] = (restoreDB && !fromDB) ? "CSV" : "DB";
            dicSettings["REPLAY_POPUP"] = "1";
            dicSettings["TRADING_MODE"] = (restoreDB && fromDB) ? "IMPORT_UAT" : "IMPORT";
            dicSettings["SAMPLING_MS"] = "1000";
            dicSettings["FX_GBPUSD"] = "GBPUSD:CS.D.GBPUSD.TODAY.IP";
            dicSettings["FX_GBPEUR"] = "GBPEUR:CS.D.GBPEUR.TODAY.IP";
            dicSettings["FX_EURUSD"] = "EURUSD:CS.D.EURUSD.TODAY.IP";
            dicSettings["FX_USDJPY"] = "USDJPY:CS.D.USDJPY.TODAY.IP";
            dicSettings["FX_AUDUSD"] = "AUDUSD:CS.D.AUDUSD.TODAY.IP";
            Config.Settings = dicSettings;

            while (start <= end)
            {
                Config.Settings["PUBLISHING_START_TIME"] = string.Format("{0}-{1}-{2} {3}:{4}:{5}", start.Year, start.Month, start.Day, 5, 45, 0);
                Config.Settings["PUBLISHING_STOP_TIME"] = string.Format("{0}-{1}-{2} {3}:{4}:{5}", start.Year, start.Month, start.Day, 22, 0, 0);
                Config.Settings["TRADING_START_TIME"] = string.Format("{0}-{1}-{2} {3}:{4}:{5}", start.Year, start.Month, start.Day, 7, 0, 0);
                Config.Settings["TRADING_STOP_TIME"] = string.Format("{0}-{1}-{2} {3}:{4}:{5}", start.Year, start.Month, start.Day, 21, 0, 0);
                Config.Settings["TRADING_CLOSING_TIME"] = string.Format("{0}-{1}-{2} {3}:{4}:{5}", start.Year, start.Month, start.Day, 17, 0, 0);
                if (deleteDB)
                    Config.Settings["DELETEDB"] = "1";
                else
                {
                    if (!restoreDB)
                    {
                        if (wholeMonth)
                            Config.Settings["PUBLISHING_CSV"] = string.Format("..\\..\\..\\MktData\\mktdata_{0}_{1}.csv", start.Month, start.Year);
                        else
                            Config.Settings["PUBLISHING_CSV"] = string.Format("..\\..\\..\\MktData\\mktdata_{0}_{1}_{2}.csv", start.Day, start.Month, start.Year);
                    }
                    if (!fromDB)
                    {
                        List<string> mktdataFiles = new List<string>();
                        if (wholeMonth)
                            mktdataFiles.Add(string.Format("..\\..\\..\\MktData\\mktdata_audusd_{0}_{1}.csv", start.Month, start.Year));
                        else
                            mktdataFiles.Add(string.Format("..\\..\\..\\MktData\\mktdata_{0}_{1}_{2}.csv", start.Day, start.Month, start.Year));
                        Config.Settings["REPLAY_CSV"] = Config.TestList(mktdataFiles);
                    }
                }

                MarketDataConnection.Instance.Connect(null);

                var lstIndices = new List<MarketData>();
                var gbpusd = new MarketData(dicSettings["FX_GBPUSD"]);
                var gbpeur = new MarketData(dicSettings["FX_GBPEUR"]);
                var eurusd = new MarketData(dicSettings["FX_EURUSD"]);
                var usdjpy = new MarketData(dicSettings["FX_USDJPY"]);
                var audusd = new MarketData(dicSettings["FX_AUDUSD"]);
                lstIndices.Add(gbpusd);
                lstIndices.Add(gbpeur);
                lstIndices.Add(eurusd);
                lstIndices.Add(usdjpy);
                lstIndices.Add(audusd);
                /*
                var indexDAX = new MarketData("DAX:IX.D.DAX.DAILY.IP");
                indexDAX.Subscribe(OnUpdate, null);
                var indexCAC = new MarketData("CAC:IX.D.CAC.DAILY.IP");
                indexCAC.Subscribe(OnUpdate, null);
                var indexDOW = new MarketData("DOW:IX.D.DOW.DAILY.IP");
                indexDOW.Subscribe(OnUpdate, null);
                var indexNYSE_DOW = new MarketData("DOW:IceConnection.DOW", "IX.D.DOW.DAILY.IP");
                //indexNYSE_DOW.Subscribe(OnUpdate, null);
                lstIndices.Add(indexDAX);
                lstIndices.Add(indexCAC);
                lstIndices.Add(indexDOW);*/

                var lstIndicators = new List<IndicatorLevel>();
                foreach (var index in lstIndices){
                    lstIndicators.Add(new IndicatorLow(index));
                    lstIndicators.Add(new IndicatorHigh(index));
                    lstIndicators.Add(new IndicatorCloseBid(index));
                    lstIndicators.Add(new IndicatorCloseOffer(index));
                    lstIndicators.Add(new IndicatorLevelPivot(index));
                    lstIndicators.Add(new IndicatorLevelR1(index));
                    lstIndicators.Add(new IndicatorLevelR2(index));
                    lstIndicators.Add(new IndicatorLevelR3(index));
                    lstIndicators.Add(new IndicatorLevelS1(index));
                    lstIndicators.Add(new IndicatorLevelS2(index));
                    lstIndicators.Add(new IndicatorLevelS3(index));
                }
                foreach(var indicator in lstIndicators)
                    indicator.Subscribe(OnUpdate, null);
                foreach (MarketData mktData in lstIndices)
                    mktData.GetMarketLevels();

                MarketDataConnection.Instance.StartListening();

                foreach (var indicator in lstIndicators)
                    indicator.Publish(Config.ParseDateTimeLocal(Config.Settings["PUBLISHING_STOP_TIME"]));
                MarketDataConnection.Instance.StopListening();

                foreach (var indicator in lstIndices)
                    indicator.Clear();

                do
                {
                    start = start.AddDays(1);
                }
                while (start.DayOfWeek == DayOfWeek.Saturday || start.DayOfWeek == DayOfWeek.Sunday);
            }
        }
Exemplo n.º 38
0
 public IndicatorNearestLevel(MarketData mktData)
     : base("NearestLevel_" + mktData.Id, new List <MarketData> {
     mktData
 })
 {
 }
Exemplo n.º 39
0
        public override void Subscribe(string[] epics, IHandyTableListener tableListener)
        {
            Dictionary <string, List <CqlQuote> > priceData = GetReplayData(epics);

            if (priceData.Count == 0)
            {
                return;
            }

            Calendar dayCalendar = new Calendar(priceData.First().Value[0].t);

            foreach (var epic in epics)
            {
                // for each quote, associate the observed gains in the near future
                var mktData       = new MarketData(epic);
                var wmaLow        = new IndicatorEMA(mktData, 2);
                var wmaMid        = new IndicatorEMA(mktData, 10);
                var wmaHigh       = new IndicatorEMA(mktData, 30);
                var wmaVeryHigh   = new IndicatorEMA(mktData, 90);
                var rsiShort      = new IndicatorRSI(mktData, 1, 14);
                var rsiLong       = new IndicatorRSI(mktData, 2, 14);
                var trendShort    = new IndicatorTrend(mktData, 90, 14, false);
                var trendLong     = new IndicatorTrend(mktData, 180, 14, false);
                var wmvolLow      = new IndicatorWMVol(mktData, wmaLow, 60, 90);
                var wmvolHigh     = new IndicatorWMVol(mktData, wmaMid, 60, 90);
                var volTrendLow   = new IndicatorTrend(wmvolLow, 30, 6, true);
                var volTrendHigh  = new IndicatorTrend(wmvolHigh, 60, 6, true);
                var allIndicators = new List <IndicatorWMA>();
                allIndicators.Add(wmaLow);
                allIndicators.Add(wmaMid);
                allIndicators.Add(wmaHigh);
                allIndicators.Add(wmaVeryHigh);
                allIndicators.Add(rsiShort);
                allIndicators.Add(rsiLong);
                allIndicators.Add(trendShort);
                allIndicators.Add(trendLong);
                allIndicators.Add(wmvolLow);
                allIndicators.Add(wmvolHigh);
                allIndicators.Add(volTrendLow);
                allIndicators.Add(volTrendHigh);

                foreach (var quote in priceData[epic])
                {
                    var mktDataValue = new Price(quote.MidPrice());
                    mktData.Process(quote.t, mktDataValue);
                    foreach (var ind in allIndicators)
                    {
                        ind.Process(quote.t, mktDataValue);
                    }
                }

                var expectations     = new Dictionary <DateTime, KeyValuePair <CqlQuote, decimal> >();
                var gainDistribution = new SortedList <int, DateTime>();
                KeyValuePair <int, DateTime> minProfit = new KeyValuePair <int, DateTime>(1000000, DateTime.MinValue);
                KeyValuePair <int, DateTime> maxProfit = new KeyValuePair <int, DateTime>(-1000000, DateTime.MinValue);
                var rnd              = new Random(155);
                var tradingStart     = Config.ParseDateTimeLocal(Config.Settings["TRADING_START_TIME"]);
                var tradingStop      = Config.ParseDateTimeLocal(Config.Settings["TRADING_STOP_TIME"]);
                var wmaVeryHighStart = wmaVeryHigh.Average(tradingStart);
                var amplitude        = 100.0m;
                foreach (var quote in priceData[epic])
                {
                    if (quote.t.TimeOfDay < tradingStart.TimeOfDay || quote.t.TimeOfDay > tradingStop.TimeOfDay)
                    {
                        continue;
                    }
                    string evtName = "";
                    if (dayCalendar.IsNearEvent(mktData.Name, quote.t, ref evtName))
                    {
                        continue;
                    }
                    var futureVal = (mktData.TimeSeries.Max(quote.t.AddMinutes(5), quote.t.AddMinutes(20)) +
                                     mktData.TimeSeries.Min(quote.t.AddMinutes(5), quote.t.AddMinutes(20))) / 2m;
                    var profit = (int)Math.Round(futureVal - quote.MidPrice());
                    expectations.Add(quote.t, new KeyValuePair <CqlQuote, decimal>(quote, profit));
                    if (gainDistribution.ContainsKey(profit))
                    {
                        if ((quote.t - gainDistribution[profit]).Hours > 3 && (rnd.Next(100) == 0))
                        {
                            gainDistribution[profit] = quote.t;
                        }
                    }
                    else
                    {
                        gainDistribution[profit] = quote.t;
                    }
                    if (profit < minProfit.Key)
                    {
                        minProfit = new KeyValuePair <int, DateTime>(profit, gainDistribution[profit]);
                    }
                    if (profit > maxProfit.Key)
                    {
                        maxProfit = new KeyValuePair <int, DateTime>(profit, gainDistribution[profit]);
                    }
                    quote.b = (quote.b - wmaVeryHighStart.Bid) / amplitude;
                    quote.o = (quote.o - wmaVeryHighStart.Offer) / amplitude;
                }
                gainDistribution = new SortedList <int, DateTime>((from elt in gainDistribution
                                                                   where !isTooClose(elt, gainDistribution)
                                                                   select elt).ToDictionary(keyVal => keyVal.Key, keyVal => keyVal.Value));
                int nbPoints  = 10;
                int idxProfit = 0;
                KeyValuePair <int, DateTime> nextProfit = minProfit;
                var selection = new SortedList <DateTime, KeyValuePair <int, CqlQuote> >();
                while (idxProfit++ < nbPoints)
                {
                    selection.Add(gainDistribution[nextProfit.Key], new KeyValuePair <int, CqlQuote>(nextProfit.Key, expectations[gainDistribution[nextProfit.Key]].Key));
                    var nextKeyVal = gainDistribution.FirstOrDefault(keyVal => keyVal.Key > nextProfit.Key &&
                                                                     keyVal.Key >= ((decimal)minProfit.Key + (decimal)idxProfit * (decimal)(maxProfit.Key - minProfit.Key) / (decimal)nbPoints));
                    if (nextKeyVal.Equals(default(KeyValuePair <int, DateTime>)))
                    {
                        break;
                    }
                    nextProfit = nextKeyVal;
                }
                foreach (var dt in selection.Keys)
                {
                    bool allValid = true;
                    foreach (var ind in allIndicators)
                    {
                        if (ind.TimeSeries[dt] == null)
                        {
                            allValid = false;
                            break;
                        }
                    }
                    if (!allValid)
                    {
                        continue;
                    }
                    PublisherConnection.Instance.Insert(dt, wmaLow, (wmaLow.TimeSeries[dt].Value.Value.Mid() - wmaVeryHighStart.Mid()) / amplitude);
                    PublisherConnection.Instance.Insert(dt, wmaMid, (wmaMid.TimeSeries[dt].Value.Value.Mid() - wmaVeryHighStart.Mid()) / amplitude);
                    PublisherConnection.Instance.Insert(dt, wmaHigh, (wmaHigh.TimeSeries[dt].Value.Value.Mid() - wmaVeryHighStart.Mid()) / amplitude);
                    PublisherConnection.Instance.Insert(dt, wmaVeryHigh, (wmaVeryHigh.TimeSeries[dt].Value.Value.Mid() - wmaVeryHighStart.Mid()) / amplitude);
                    PublisherConnection.Instance.Insert(dt, rsiShort, (rsiShort.TimeSeries[dt].Value.Value.Mid() - 50m) / amplitude);
                    PublisherConnection.Instance.Insert(dt, rsiLong, (rsiLong.TimeSeries[dt].Value.Value.Mid() - 50m) / amplitude);
                    PublisherConnection.Instance.Insert(dt, trendShort, trendShort.TimeSeries[dt].Value.Value.Mid() / 1000m);
                    PublisherConnection.Instance.Insert(dt, trendLong, trendLong.TimeSeries[dt].Value.Value.Mid() / 1000m);
                    PublisherConnection.Instance.Insert(dt, wmvolLow, wmvolLow.TimeSeries[dt].Value.Value.Mid() / 10m);
                    PublisherConnection.Instance.Insert(dt, wmvolHigh, wmvolHigh.TimeSeries[dt].Value.Value.Mid() / 10m);
                    PublisherConnection.Instance.Insert(dt, volTrendLow, volTrendLow.TimeSeries[dt].Value.Value.Mid());
                    PublisherConnection.Instance.Insert(dt, volTrendHigh, volTrendHigh.TimeSeries[dt].Value.Value.Mid());
                    PublisherConnection.Instance.Insert(dt, epic, new Value((double)selection[dt].Key / ((double)amplitude / 2.0)));
                }
                priceData[epic] = selection.Values.Select(kv => kv.Value).ToList();
            }
            replay(priceData, tableListener);
        }
Exemplo n.º 40
0
 public IndicatorLow(MarketData mktData)
     : base(mktData, "Low")
 {
 }
Exemplo n.º 41
0
 public SignalMole(MarketData asset, int lowPeriod, int midPeriod, int highPeriod, IndicatorEMA low = null, IndicatorEMA high = null, MarketData tradingIndex = null)
     : base("Mole_" + lowPeriod + "_" + midPeriod + "_" + highPeriod + "_" + asset.Id, asset, lowPeriod, midPeriod, low, high, tradingIndex)
 {
 }
Exemplo n.º 42
0
 public virtual void SubscribeMarketData(MarketData mktData)
 {
     if (_mktDataListener.MarketData.Select(mktdata => mktdata.Id).Contains(mktData.Id))
         UnsubscribeMarketData(_mktDataListener.MarketData.Where(mktdata => mktdata.Id == mktData.Id).First());
     _mktDataListener.MarketData.Add(mktData);
     Log.Instance.WriteEntry("Subscribed " + mktData.Name + " to " + mktData.Id);
 }
Exemplo n.º 43
0
 protected override bool Process(MarketData indicator, DateTime updateTime, Price value, ref Signal.Tick tradingOrder)
 {
     if (base.Process(indicator, updateTime, value, ref tradingOrder))
     {
         if (_trendAssumption != SIGNAL_CODE.BUY && tradingOrder == _onSell)
         {
             if (_low.TimeSeries.Count >= 2)
             {
                 var lowVal     = _low.TimeSeries[updateTime].Value.Value;
                 var prevValues = _low.TimeSeries.Values(updateTime, new TimeSpan(0, 1, 0), true);
                 if (prevValues != null)
                 {
                     if (prevValues.Count >= 2)
                     {
                         var prevVal = prevValues[prevValues.Count - 2].Value;
                         if (_cascading)
                         {
                             if (_localMinimum > lowVal.Bid)
                             {
                                 _localMinimum = lowVal.Bid;
                             }
                             if (_localMaximum < lowVal.Bid)
                             {
                                 _localMaximum = lowVal.Bid;
                             }
                             if (_buying)
                             {
                                 if (lowVal.Bid < _localMaximum - _threshold)
                                 {
                                     _pivot        = _localMaximum;
                                     _localMinimum = _localMaximum;
                                     _buying       = false;
                                 }
                                 else if (lowVal.Bid > _pivot + _threshold)
                                 {
                                     _signalCode  = SIGNAL_CODE.BUY;
                                     tradingOrder = _onBuy;
                                 }
                             }
                             else
                             {
                                 if (lowVal.Bid > _localMinimum + _threshold)
                                 {
                                     _pivot        = _localMinimum;
                                     _localMaximum = _localMinimum;
                                     _signalCode   = SIGNAL_CODE.BUY;
                                     tradingOrder  = _onBuy;
                                     _buying       = true;
                                 }
                             }
                         }
                         else
                         {
                             _cascading    = true;
                             _localMinimum = lowVal.Bid;
                             _localMaximum = lowVal.Bid;
                             _pivot        = _localMaximum;
                             _buying       = false;
                         }
                         return(true);
                     }
                 }
             }
         }
         else if (_trendAssumption != SIGNAL_CODE.SELL && tradingOrder == _onBuy)
         {
             if (_low.TimeSeries.Count >= 2)
             {
                 var lowVal     = _low.TimeSeries[updateTime].Value.Value;
                 var prevValues = _low.TimeSeries.Values(updateTime, new TimeSpan(0, 1, 0), true);
                 if (prevValues != null)
                 {
                     if (prevValues.Count >= 2)
                     {
                         var prevVal = prevValues[prevValues.Count - 2].Value;
                         if (_cascading)
                         {
                             if (_localMinimum > lowVal.Offer)
                             {
                                 _localMinimum = lowVal.Offer;
                             }
                             if (_localMaximum < lowVal.Offer)
                             {
                                 _localMaximum = lowVal.Offer;
                             }
                             if (_selling)
                             {
                                 if (lowVal.Offer > _localMinimum + _threshold)
                                 {
                                     _pivot        = _localMinimum;
                                     _localMaximum = _localMinimum;
                                     _selling      = false;
                                 }
                                 else if (lowVal.Offer < _pivot - _threshold)
                                 {
                                     _signalCode  = SIGNAL_CODE.SELL;
                                     tradingOrder = _onSell;
                                 }
                             }
                             else
                             {
                                 if (lowVal.Offer < _localMaximum - _threshold)
                                 {
                                     _pivot        = _localMaximum;
                                     _localMinimum = _localMaximum;
                                     _signalCode   = SIGNAL_CODE.SELL;
                                     tradingOrder  = _onSell;
                                     _selling      = true;
                                 }
                             }
                         }
                         else
                         {
                             _cascading    = true;
                             _localMinimum = lowVal.Offer;
                             _localMaximum = lowVal.Offer;
                             _pivot        = _localMinimum;
                             _selling      = false;
                         }
                         return(true);
                     }
                 }
             }
         }
         _cascading = false;
         _buying    = false;
         _selling   = false;
         return(true);
     }
     return(false);
 }
Exemplo n.º 44
0
 protected override Price IndicatorFunc(MarketData mktData, DateTime updateTime, Price value)
 {
     return CalcRSI(mktData, updateTime);
 }
Exemplo n.º 45
0
 protected void OnUpdate(MarketData mktData, DateTime updateTime, Price value)
 {
     Signal.Tick tradingOrder = _onHold;
     bool signaled = Process(mktData, updateTime, value, ref tradingOrder);
     if (signaled)
     {
         // send a signal
         var stockValue = _asset.TimeSeries[updateTime].Value.Value;
         if (tradingOrder(this, updateTime, stockValue))
         {
             if (_signalCode == SIGNAL_CODE.BUY)
                 PublisherConnection.Instance.Insert(updateTime, this, _signalCode, stockValue.Offer);
             else if (_signalCode == SIGNAL_CODE.SELL)
                 PublisherConnection.Instance.Insert(updateTime, this, _signalCode, stockValue.Bid);
             else if (_signalCode == SIGNAL_CODE.FAILED)
                 PublisherConnection.Instance.Insert(updateTime, this, _signalCode, stockValue.Bid);
         }
     }
 }
Exemplo n.º 46
0
 public IndicatorRSI(MarketData mktData, int subPeriodMinutes, int nbPeriods)
     : base("RSI_" + subPeriodMinutes + "_" + nbPeriods + "_" + mktData.Id, mktData, nbPeriods * subPeriodMinutes)
 {
     _subPeriodSeconds = subPeriodMinutes * 60;
     _nbPeriods = nbPeriods;
 }
Exemplo n.º 47
0
 public SignalALaCon(MarketData fx)
     : base("CON_" + fx.Id, fx)
 {
     _mktIndicator.Add(new IndicatorRSI(fx, 1, 14));
 }
Exemplo n.º 48
0
 bool isIG(MarketData mktData)
 {
     return(mktData.Id.StartsWith("IX.") || mktData.Id.StartsWith("CS."));
 }
Exemplo n.º 49
0
        public static void Run(bool generate = false, bool generate_from_db = false)
        {
            Dictionary<string, string> dicSettings = new Dictionary<string, string>();
            dicSettings["APP_NAME"] = "Midax";
            dicSettings["PUBLISHING_START_TIME"] = "2016-01-22 08:00:00";
            dicSettings["PUBLISHING_STOP_TIME"] = "2016-01-22 09:00:00";
            dicSettings["REPLAY_MODE"] = "CSV";
            dicSettings["REPLAY_POPUP"] = "1";
            dicSettings["TRADING_START_TIME"] = "2016-01-22 08:45:00";
            dicSettings["TRADING_STOP_TIME"] = "2016-01-22 08:59:00";
            dicSettings["TRADING_CLOSING_TIME"] = "2016-01-22 08:57:00";
            dicSettings["TRADING_MODE"] = "REPLAY";
            dicSettings["TRADING_SIGNAL"] = "MacD_1_5_IX.D.DAX.DAILY.IP";
            dicSettings["TRADING_LIMIT_PER_BP"] = "10";
            dicSettings["TRADING_CURRENCY"] = "GBP";
            Config.Settings = dicSettings;

            string action = generate ? "Generating" : "Testing";
            var dax = new MarketData("DAX:IX.D.DAX.DAILY.IP");
            List<string> tests = new List<string>();

            Console.WriteLine(action + " WMA...");
            // Test weighted moving average with long intervals
            tests.Add(@"..\..\expected_results\testWMA.csv");
            dicSettings["REPLAY_CSV"] = Config.TestList(tests);
            if (generate)
                dicSettings["PUBLISHING_CSV"] = string.Format("..\\..\\expected_results\\testWMAgen.csv");
            var macDTestWMA = new ModelMacDTest(dax, 1, 2, 3);
            MarketDataConnection.Instance.Connect(null);
            macDTestWMA.StartSignals();
            macDTestWMA.StopSignals();

            // Test weighted moving average with short intervals
            tests = new List<string>();
            tests.Add(@"..\..\expected_results\testWMA2.csv");
            dicSettings["REPLAY_CSV"] = Config.TestList(tests);
            if (generate)
                dicSettings["PUBLISHING_CSV"] = string.Format("..\\..\\expected_results\\testWMA2gen.csv");
            dax.Clear();
            macDTestWMA = new ModelMacDTest(dax, 1, 2, 3);
            MarketDataConnection.Instance.Connect(null);
            macDTestWMA.StartSignals();
            macDTestWMA.StopSignals();

            // Test weighted moving average with linear time decay
            tests = new List<string>();
            tests.Add(@"..\..\expected_results\testWMA3.csv");
            dicSettings["REPLAY_CSV"] = Config.TestList(tests);
            dicSettings["TIME_DECAY_FACTOR"] = "3";
            if (generate)
                dicSettings["PUBLISHING_CSV"] = string.Format("..\\..\\expected_results\\testWMA3gen.csv");
            dax.Clear();
            macDTestWMA = new ModelMacDTest(dax, 1, 2, 3);
            MarketDataConnection.Instance.Connect(null);
            macDTestWMA.StartSignals();
            macDTestWMA.StopSignals();

            // Test volume weighted moving average with linear time decay
            /*
            tests = new List<string>();
            tests.Add(@"..\..\expected_results\testWMA4.csv");
            dicSettings["REPLAY_CSV"] = Config.TestList(tests);
            if (generate)
                dicSettings["PUBLISHING_CSV"] = string.Format("..\\..\\expected_results\\testWMA4gen.csv");
            var macDVTest = new ModelMacDVTest(dax, 1, 2, 3);
            MarketDataConnection.Instance.Connect(null);
            macDVTest.StartSignals();
            macDVTest.StopSignals();*/
            dicSettings.Remove("TIME_DECAY_FACTOR");

            // Test RSI and Correlation indicators
            tests = new List<string>();
            tests.Add(@"..\..\expected_results\testRsiCorrel.csv");
            dicSettings["INDEX_ICEDOW"] = "DOW:IceConnection_DOW";
            dicSettings["INDEX_DOW"] = "DOW:IX.D.DOW.DAILY.IP";
            dicSettings["INDEX_DAX"] = "DAX:IX.D.DAX.DAILY.IP";
            dicSettings["REPLAY_CSV"] = Config.TestList(tests);
            if (generate)
                dicSettings["PUBLISHING_CSV"] = string.Format("..\\..\\expected_results\\testRsiCorrelgen.csv");
            dax.Clear();
            var icedow = new MarketData(dicSettings["INDEX_ICEDOW"]);
            var dow = new MarketData(dicSettings["INDEX_DOW"]);
            var macD = new ModelMacDTest(dax, 1, 2, 3);
            //var macDV = new ModelMacDVTest(icedow, 1, 2, 3, dow);
            var moleTest = new ModelMoleTest(macD);
            MarketDataConnection.Instance.Connect(null);
            macD.StartSignals(false);
            //macDV.StartSignals(false);
            moleTest.StartSignals(false);
            MarketDataConnection.Instance.StartListening();
            moleTest.StopSignals(false);
            //macDV.StartSignals(false);
            macD.StopSignals(false);
            MarketDataConnection.Instance.StopListening();

            Console.WriteLine(action + " calibration...");

            // Test a 1mn linear regression
            var mktData = new MarketData("testLRMktData");
            var updateTime = Config.ParseDateTimeLocal(dicSettings["TRADING_START_TIME"]);
            mktData.TimeSeries.Add(updateTime, new Price(100));
            mktData.TimeSeries.Add(updateTime.AddSeconds(20), new Price(120));
            mktData.TimeSeries.Add(updateTime.AddSeconds(40), new Price(140));
            mktData.TimeSeries.Add(updateTime.AddSeconds(60), new Price(130));
            mktData.TimeSeries.Add(updateTime.AddSeconds(80), new Price(145));
            mktData.TimeSeries.Add(updateTime.AddSeconds(100), new Price(165));
            mktData.TimeSeries.Add(updateTime.AddSeconds(120), new Price(145));
            var linReg = new IndicatorLinearRegression(mktData, new TimeSpan(0, 2, 0));
            var linRegCoeff = linReg.linearCoeff(updateTime.AddSeconds(120));
            if (Math.Abs(linRegCoeff.Value - 0.821428571428573m) > 1e-8m)
                throw new ApplicationException("Linear regression error");

            // Test the optimization of function a * cos(b * x) + b * sin(a * x) using Levenberg Marquardt
            LevenbergMarquardt.objective_func objFunc = (NRealMatrix x) => { NRealMatrix y = new NRealMatrix(x.Rows, 1);
                                                 for (int idxRow = 0; idxRow < y.Rows; idxRow++)
                                                     y.SetAt(idxRow, 0, new NDouble(2 * Math.Cos(x[idxRow, 0]) + Math.Sin(2 * x[idxRow, 0])));
                                                 return y; };
            List<double> inputs = new List<double>();
            Random rnd = new Random(155);
            for (int idxPt = 0; idxPt < 10; idxPt++)
                inputs.Add(rnd.NextDouble() * 2);
            List<Value> modelParams = new List<Value>();
            modelParams.Add(new Value(-0.2)); modelParams.Add(new Value(0.3));
            LevenbergMarquardt.model_func modelFunc = (NRealMatrix x, NRealMatrix weights) => { NRealMatrix y = new NRealMatrix(x.Rows, 1);
                                                double a = weights[0, 0]; double b = weights[0, 1];
                                                for (int idxRow = 0; idxRow < y.Rows; idxRow++)
                                                     y.SetAt(idxRow, 0, new NDouble(a * Math.Cos(b * x[idxRow, 0]) + b * Math.Sin(a * x[idxRow, 0])));
                                                return y; };
            Func<double,double,double,double> derA = (double a, double b, double x) => Math.Cos(b * x) + b * x * Math.Cos(a * x);
            Func<double,double,double,double> derB = (double a, double b, double x) => - a * x * Math.Sin(b * x) + Math.Sin(a * x);
            LevenbergMarquardt.model_func jacFunc = (NRealMatrix x, NRealMatrix weights) =>
            {
                NRealMatrix jac = new NRealMatrix(x.Rows, 2);
                double a = weights[0, 0]; double b = weights[0, 1];
                for (int idxRow = 0; idxRow < jac.Rows; idxRow++)
                {
                    jac.SetAt(idxRow, 0, new NDouble(-derA(a, b, x[idxRow, 0])));
                    jac.SetAt(idxRow, 1, new NDouble(-derB(a, b, x[idxRow, 0])));
                }
                return jac;
            };
            LevenbergMarquardt calibModel = new LevenbergMarquardt(objFunc, inputs, modelParams, modelFunc, jacFunc);
            calibModel.Solve();
            if (Math.Abs(modelParams[0].X - 2) > calibModel.ObjectiveError || Math.Abs(modelParams[1].X - 1) > calibModel.ObjectiveError)
                throw new ApplicationException("LevenbergMarquardt calibration error");

            // Parity-2 problem
            NeuralNetwork ann = new NeuralNetwork(2, 1, new List<int>() { 2 });
            List<List<double>> annInputs = new List<List<double>>();
            annInputs.Add(new List<double>() { -1, -1 });
            annInputs.Add(new List<double>() { -1, 1 });
            annInputs.Add(new List<double>() { 1, -1 });
            annInputs.Add(new List<double>() { 1, 1 });
            List<List<double>> annOutputs = new List<List<double>>();
            annOutputs.Add(new List<double>() { 1 });
            annOutputs.Add(new List<double>() { -1 });
            annOutputs.Add(new List<double>() { -1 });
            annOutputs.Add(new List<double>() { 1 });
            // test forward propagation
            ann._outputs.Neurons[0].Weights[0].X = 1;
            ann._outputs.Neurons[0].Weights[1].X = -1;
            ann._outputs.Neurons[0].Weights[2].X = -1;
            ann._innerLayers[0].Neurons[0].Weights[0].X = 1;
            ann._innerLayers[0].Neurons[0].Weights[1].X = 1;
            ann._innerLayers[0].Neurons[0].Weights[2].X = 1;
            ann._innerLayers[0].Neurons[1].Weights[0].X = 1;
            ann._innerLayers[0].Neurons[1].Weights[1].X = 1;
            ann._innerLayers[0].Neurons[1].Weights[2].X = -1;
            ann._inputs.Neurons[0].Value.X = -1;
            ann._inputs.Neurons[1].Value.X = -1;
            if (Math.Abs(ann._outputs.Neurons[0].Activation() - -0.38873457229297215) > calibModel.ObjectiveError)
                throw new ApplicationException("Neural network forward propagation error");
            // Test neural network training for parity-2 problem
            ann = new NeuralNetwork(2, 1, new List<int>() { 2 });
            ann.Train(annInputs, annOutputs);

            // Test neural network training for parity-3 problem
            ann = new NeuralNetwork(3, 1, new List<int>() { 2 });
            annInputs = new List<List<double>>();
            annInputs.Add(new List<double>() {-1,-1,-1});
            annInputs.Add(new List<double>() {-1,-1, 1});
            annInputs.Add(new List<double>() {-1, 1,-1});
            annInputs.Add(new List<double>() {-1, 1, 1});
            annInputs.Add(new List<double>() { 1,-1,-1});
            annInputs.Add(new List<double>() { 1,-1, 1});
            annInputs.Add(new List<double>() { 1, 1,-1});
            annInputs.Add(new List<double>() { 1, 1, 1});
            annOutputs = new List<List<double>>();
            annOutputs.Add(new List<double>() { -1 });
            annOutputs.Add(new List<double>() {  1 });
            annOutputs.Add(new List<double>() {  1 });
            annOutputs.Add(new List<double>() { -1 });
            annOutputs.Add(new List<double>() {  1 });
            annOutputs.Add(new List<double>() { -1 });
            annOutputs.Add(new List<double>() { -1 });
            annOutputs.Add(new List<double>() {  1 });
            ann.Train(annInputs, annOutputs);

            Console.WriteLine(action + " live indicators and signals...");
            tests = new List<string>();
            tests.Add(@"..\..\expected_results\core_22_1_2016.csv");
            if (generate_from_db)
                dicSettings["DB_CONTACTPOINT"] = "192.168.1.26";
            dicSettings["REPLAY_MODE"] = generate_from_db ? "DB" : "CSV";
            dicSettings["REPLAY_CSV"] = Config.TestList(tests);
            if (generate)
                dicSettings["PUBLISHING_CSV"] = string.Format("..\\..\\expected_results\\coregen_22_1_2016.csv");
            MarketDataConnection.Instance.Connect(null);
            dax.Clear();
            var model = new ModelMacDTest(dax);
            model.StartSignals();

            Console.WriteLine(action + " daily indicators...");
            model.StopSignals();
            Thread.Sleep(1000);

            if (!dicSettings.ContainsKey("PUBLISHING_CSV"))
            {
                // the program is expected to throw exceptions in this scope, just press continue if you are debugging
                // all exceptions should be handled, and the program should terminate with a success message box

                // test that the right numer of trades was placed. this is an extra sanity check to make sure the program is not idle
                if (ReplayTester.Instance.NbProducedTrades != ReplayTester.Instance.NbExpectedTrades)
                    model.ProcessError(string.Format("the model did not produced the expected number of trades. It produced {0} trades instead of {1} expected",
                                                    ReplayTester.Instance.NbProducedTrades, ReplayTester.Instance.NbExpectedTrades));

                // test trade booking
                MarketDataConnection.Instance = new ReplayConnection();
                model = new ModelMacDTest(dax);
                MarketDataConnection.Instance.Connect(null);
                Console.WriteLine(action + " trade booking...");
                var tradeTime = Config.ParseDateTimeLocal(dicSettings["TRADING_CLOSING_TIME"]).AddSeconds(-1);
                var tradeTest = new Trade(tradeTime, dax.Id, SIGNAL_CODE.SELL, 10, 10000m);
                var expectedTrades = new Dictionary<KeyValuePair<string, DateTime>, Trade>();
                expectedTrades[new KeyValuePair<string, DateTime>("###DUMMY_TRADE_REF1###", tradeTime)] = tradeTest;
                ReplayTester.Instance.SetExpectedResults(null, null, expectedTrades, null);
                model.PTF.Subscribe();
                model.PTF.BookTrade(tradeTest);
                Thread.Sleep(1000);
                if (model.PTF.GetPosition(tradeTest.Epic).Quantity != -10)
                    throw new ApplicationException("SELL Trade booking error");
                var expectedTrade = new Trade(tradeTime, dax.Id, SIGNAL_CODE.BUY, 10, 10000m);
                expectedTrade.Reference = "###CLOSE_DUMMY_TRADE_REF2###";
                expectedTrade.Id = "###DUMMY_TRADE_ID1###";
                expectedTrades[new KeyValuePair<string, DateTime>(expectedTrade.Reference, tradeTime)] = expectedTrade;
                model.PTF.ClosePosition(tradeTest, tradeTime);
                Thread.Sleep(1000);
                if (model.PTF.GetPosition(tradeTest.Epic).Quantity != 0)
                    throw new ApplicationException("Trade position closing error");
                expectedTrade.Reference = "###DUMMY_TRADE_REF3###";
                expectedTrade.Id = "###DUMMY_TRADE_ID2###";
                expectedTrades[new KeyValuePair<string, DateTime>(expectedTrade.Reference, tradeTime)] = expectedTrade;
                model.PTF.BookTrade(new Trade(tradeTest, true, tradeTime));
                Thread.Sleep(1000);
                if (model.PTF.GetPosition(tradeTest.Epic).Quantity != 10)
                    throw new ApplicationException("BUY Trade booking error");
                expectedTrade = new Trade(tradeTime, dax.Id, SIGNAL_CODE.SELL, 10, 0m);
                expectedTrade.Reference = "###CLOSE_DUMMY_TRADE_REF4###";
                expectedTrade.Id = "###DUMMY_TRADE_ID2###";
                expectedTrades[new KeyValuePair<string, DateTime>(expectedTrade.Reference, tradeTime)] = expectedTrade;
                Portfolio.Instance.CloseAllPositions(tradeTest.TradingTime);
                Thread.Sleep(1000);

                // test synchronization issues with the broker
                List<string> testsSync = new List<string>();
                testsSync.Add(@"..\..\expected_results\sync.csv");
                dicSettings["REPLAY_CSV"] = Config.TestList(testsSync);
                MarketDataConnection.Instance = new ReplayCrazySeller();
                model = new ModelMacDTest(dax);
                Console.WriteLine(action + " synchronization...");
                MarketDataConnection.Instance.Connect(null);
                model.StartSignals();
                model.StopSignals();
                testsSync = new List<string>();
                testsSync.Add(@"..\..\expected_results\sync2.csv");
                dicSettings["REPLAY_CSV"] = Config.TestList(testsSync);
                MarketDataConnection.Instance = new ReplayCrazyBuyer();
                model = new ModelMacDTest(dax);
                MarketDataConnection.Instance.Connect(null);
                model.StartSignals();
                model.StopSignals();

                Console.WriteLine(action + " expected exceptions...");
                dicSettings["REPLAY_CSV"] = Config.TestList(tests);
                MarketDataConnection.Instance = new ReplayConnection();
                MarketDataConnection.Instance.Connect(null);
                List<string> testError = new List<string>();
                testError.Add(@"..\..\expected_results\error.csv");
                dicSettings["REPLAY_CSV"] = Config.TestList(testError);
                var modelErr = new ModelMacDTest(dax);
                string expected;
                bool success = false;
                try
                {
                    MarketDataConnection.Instance.Connect(null);
                    modelErr.StartSignals();
                }
                catch (Exception exc)
                {
                    expected = "Test failed: indicator EMA_1_IX.D.DAX.DAILY.IP time 08:30 expected value 9740.300000000000000000000000 != 9739.8";
                    success = (exc.Message.Replace(" AM", "") == expected);
                    if (!success)
                        model.ProcessError(exc.Message, expected);
                }
                if (!success)
                    model.ProcessError("An expected exception has not been thrown");
                success = false;
                try
                {
                    modelErr.StopSignals();
                }
                catch (Exception exc)
                {
                    model.ProcessError(exc.Message + " - Wrong daily mean exception removed");
                }
                success = false;
                try
                {
                    model.StopSignals();
                }
                catch (Exception exc)
                {
                    model.ProcessError(exc.Message + " - Double EOD publishing exception removed");
                }
                success = false;
                try
                {
                    MarketDataConnection.Instance = new ReplayConnection();
                    MarketDataConnection.Instance.Connect(null);
                    model = new ModelMacDTest(new MarketData(dax.Id));
                    model.StartSignals();
                }
                catch (Exception exc)
                {
                    expected = "Test failed: indicator EMA_1_IX.D.DAX.DAILY.IP time 08:30 expected value 9740.300000000000000000000000 != 9739.8";
                    success = (exc.Message.Replace(" AM", "") == expected);
                    if (!success)
                        model.ProcessError(exc.Message, expected);
                }
                if (!success)
                    model.ProcessError("An expected exception has not been thrown");
                success = false;
                try
                {
                    MarketDataConnection.Instance.Resume();
                }
                catch (Exception exc)
                {
                    expected = "Time series do not accept values in the past";
                    success = (exc.Message.Replace(" AM", "") == expected);
                    if (!success)
                        model.ProcessError(exc.Message, expected);
                }
                if (!success)
                    model.ProcessError("An expected exception has not been thrown");
                model.StopSignals();
                success = false;
            }
        }
Exemplo n.º 50
0
 protected virtual void OnUpdateMktData(MarketData mktData, DateTime updateTime, Price value)
 {
 }
Exemplo n.º 51
0
 public abstract void Insert(DateTime updateTime, MarketData mktData, Price price);
Exemplo n.º 52
0
 protected virtual void OnUpdateIndicator(MarketData mktData, DateTime updateTime, Price value)
 {
 }
Exemplo n.º 53
0
 public IndicatorHigh(MarketData mktData)
     : base(mktData, "High")
 {
 }
Exemplo n.º 54
0
 protected override Price IndicatorFunc(MarketData mktData, DateTime updateTime, Price value)
 {
     return(Average(updateTime));
 }
Exemplo n.º 55
0
 public virtual void UnsubscribeMarketData(MarketData mktData)
 {
     var lstRemove = _mktDataListener.MarketData.Where(mktdata => mktdata.Id == mktData.Id).ToList();
     foreach (var selmktdata in lstRemove)
     {
         _mktDataListener.MarketData.Remove(selmktdata);
         Log.Instance.WriteEntry("Unsubscribed " + selmktdata.Name + " from " + selmktdata.Id);
     }
 }
Exemplo n.º 56
0
 public SignalANNWMA_5_2(MarketData asset, List<Indicator> indicators, List<decimal> weights)
     : base(asset, "WMA_5_2", 1, indicators, weights)
 {
 }
Exemplo n.º 57
0
 protected override void OnUpdate(MarketData mktData, DateTime updateTime, Price value)
 {
     Price rsi = IndicatorFunc(mktData, updateTime, value);
     if (rsi != null)
     {
         _values.Add(updateTime, rsi);
         Publish(updateTime, rsi.Bid);
     }
 }
Exemplo n.º 58
0
 public ModelMacDV(MarketData index, int lowPeriod = 2, int midPeriod = 10, int highPeriod = 60, MarketData tradingIndex = null) :
     base(index, lowPeriod, midPeriod, highPeriod, tradingIndex)
 {
 }
Exemplo n.º 59
0
 public Price CalcRSI(MarketData mktData, DateTime updateTime)
 {
     if (updateTime >= _nextRsiTime)
     {
         if (mktData.TimeSeries.Count < 2)
             return null;
         if (_nextRsiTime == DateTime.MinValue)
             _nextRsiTime = updateTime.AddSeconds(_subPeriodSeconds);
         else
             _nextRsiTime = _nextRsiTime.AddSeconds(_subPeriodSeconds);
         DateTime rsiTime = _nextRsiTime.AddSeconds(-_subPeriodSeconds);
         if (mktData.TimeSeries.StartTime() > rsiTime)
             return null;
         if (_rsiCandles.Count == _nbPeriods)
             _rsiCandles.RemoveAt(0);
         if (_history.Count == 120)
             _history.RemoveAt(0);
         if (_rsiCandles.Count > 0){
             _curCandle.EndTime = updateTime;
             var curStartRsi = _rsiCandles[_rsiCandles.Count - 1].StartRsiValue + (_rsiCandles[_rsiCandles.Count - 1].GainRsi ? _rsiCandles[_rsiCandles.Count - 1].DiffRsi:
                                     -_rsiCandles[_rsiCandles.Count - 1].DiffRsi);
             _curCandle = new RsiCandle(curStartRsi, mktData.TimeSeries.Last().Mid());
         }
         else
             _curCandle = new RsiCandle(50m, mktData.TimeSeries.Last().Mid());
         _rsiCandles.Add(_curCandle);
         _history.Add(_curCandle);
     }
     else
         _curCandle = _rsiCandles.Last();
     DateTime startTime = _nextRsiTime.AddSeconds(-_subPeriodSeconds);
     if (mktData.TimeSeries.StartTime() > startTime)
         return null;
     var prevValStart = mktData.TimeSeries.PrevValue(startTime);
     if (!prevValStart.HasValue)
         return null;
     Price valStart = prevValStart.Value.Value;
     Price valEnd = mktData.TimeSeries.Last();
     Price valRsiStart = prevValStart.Value.Value;
     Price valRsiEnd = mktData.TimeSeries.Last();
     if (valEnd > valStart)
     {
         _curCandle.GainAsset = true;
         _curCandle.DiffAsset = valEnd.Mid() - valStart.Mid();
     }
     else
     {
         _curCandle.GainAsset = false;
         _curCandle.DiffAsset = valStart.Mid() - valEnd.Mid();
     }
     var sumGain = 0m;
     var sumLosses = 0m;
     var nbGain = 0;
     var nbLoss = 0;
     foreach (var candle in _rsiCandles)
     {
         if (candle.GainAsset)
         {
             sumGain += candle.DiffAsset;
             nbGain++;
         }
         else
         {
             sumLosses += candle.DiffAsset;
             nbLoss++;
         }
     }
     var avgGain = nbGain == 0 ? 0 : sumGain / nbGain;
     var avgLoss = nbLoss == 0 ? 0 : sumLosses / nbLoss;
     var stdDevGain = 0m;
     var stdDevLoss = 0m;
     foreach (var candle in _rsiCandles)
     {
         if (candle.GainAsset)
             stdDevGain += (decimal)Math.Pow((double)(candle.DiffAsset - avgGain), 2.0);
         else
             stdDevLoss += (decimal)Math.Pow((double)(candle.DiffAsset - avgLoss), 2.0);
     }
     _curCandle.StdDevGain = nbGain == 0 ? 0m : (decimal)Math.Sqrt((double)stdDevGain / nbGain);
     _curCandle.StdDevLoss = nbLoss == 0 ? 0m : (decimal)Math.Sqrt((double)stdDevLoss / nbLoss);
     decimal rs = Math.Abs(sumLosses) < 0.1m ? (Math.Abs(sumGain) < 0.1m ? 1m : 1000m) : sumGain / sumLosses;
     Price rsi = new Price(100m - 100m / (1m + rs));
     if (rsi.Bid > _curCandle.StartRsiValue){
         _curCandle.GainRsi = true;
         _curCandle.DiffRsi = rsi.Bid - _curCandle.StartRsiValue;
     }
     else{
         _curCandle.GainRsi = false;
         _curCandle.DiffRsi = _curCandle.StartRsiValue - rsi.Bid;
     }
     return rsi;
 }
Exemplo n.º 60
0
        public ModelMacD(MarketData index, int lowPeriod = 2, int midPeriod = 10, int highPeriod = 60, MarketData tradingIndex = null)
        {
            if (Config.Settings.ContainsKey("ASSUMPTION_TREND"))
            {
                _trendAssumption = Config.Settings["ASSUMPTION_TREND"] == "BULL" ? SIGNAL_CODE.BUY : SIGNAL_CODE.SELL;
            }
            List <MarketData> mktData = new List <MarketData>();

            mktData.Add(index);
            _mktData      = mktData;
            _index        = index;
            _tradingIndex = tradingIndex == null ? index : tradingIndex;
            _lowPeriod    = lowPeriod;
            _midPeriod    = midPeriod;
            _highPeriod   = highPeriod;
        }