private IObservable<MarketData> GenerateStream(CurrencyPair currencyPair)
        {

            return Observable.Create<MarketData>(observer =>
            {
                var spread = currencyPair.DefaultSpread;
                var midRate = currencyPair.InitialPrice;
                var bid = midRate - (spread * currencyPair.PipSize);
                var offer = midRate + (spread * currencyPair.PipSize);
                var initial = new MarketData(currencyPair.Code, bid, offer);

                var currentPrice = initial;
                observer.OnNext(initial);

                var random = new Random();


                //for a given period, move prices by up to 5 pips
                return Observable.Interval(TimeSpan.FromSeconds(1 / (double)currencyPair.TickFrequency))
                    .Select(_ => random.Next(1, 5))
                    .Subscribe(pips =>
                    {
                        //move up or down between 1 and 5 pips
                        var adjustment = Math.Round(pips * currencyPair.PipSize, currencyPair.DecimalPlaces);
                        currentPrice = random.NextDouble() > 0.5
                                        ? currentPrice + adjustment
                                        : currentPrice - adjustment;
                        observer.OnNext(currentPrice);

                    });
            });
        }
Example #2
0
        public bool getAveragePrice(MarketData md, int qty, Side side, int leg)
        {
            long tempPrice = 0;
            long tempQty = 0;
            for (int i = 0; i < 5; ++i)
            {
                long p = md.getPrice(side, i + 1);
                long q = md.getQty(side, i + 1);

                tempPrice += p * q;
                tempQty += q;

                if (tempQty >= qty)
                    break;
            }

            if (tempQty < qty)
            {
                if (leg == 1)
                    _data.avgPriceFirstLeg = 0;
                else
                    _data.avgPriceSecondLeg = 0;
                return false;
            }
            if (leg == 1)
                _data.avgPriceFirstLeg = (int)(tempPrice / tempQty);
            else
                _data.avgPriceSecondLeg = (int)(tempPrice / tempQty);

            return true;
        }
Example #3
0
 public MarketItem(MarketData res)
 {
     resData = res;
     name = GetName(resData.itemId);
     icon = GetIcon(resData.itemId);
     if (res.wing == 1)
     {
         marketItemType = MarkItemType.WingItem;
     }
     currNum = resData.totalCount;
 }
        static bool Get_IDX_HASTC(string address, ref MarketData hastcIdx)
        {
            //bool retVal = true;
            //CultureInfo dataCulture = common.language.GetCulture("en-US");
            //HttpWebRequest wRequest = HttpWebRequest.Create(new Uri(address)) as HttpWebRequest;
            //HttpWebResponse wResponse = wRequest.GetResponse() as HttpWebResponse;
            //StreamReader reader = new StreamReader(wResponse.GetResponseStream());
            //string htmlContent = reader.ReadToEnd();
            //HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            //doc.LoadHtml(htmlContent);
            //HtmlAgilityPack.HtmlNode nodeHNXIndex = doc.GetElementbyId("IDX");
            //HtmlAgilityPack.HtmlNode nodeTongKL = doc.GetElementbyId("QTY");
            //if (nodeHNXIndex!=null)
            //     hastcIdx.Value = decimal.Parse(nodeHNXIndex.InnerHtml, dataCulture);
            //else retVal = false;
            //if (nodeTongKL != null) hastcIdx.TotalQty = decimal.Parse(nodeTongKL.InnerHtml, dataCulture);
            //else retVal = false;
            //hastcIdx.TotalAmt = 0;
            //return retVal;

            bool retVal = true;
            CultureInfo dataCulture = common.language.GetCulture("en-US");
            System.Net.WebRequest webReq = System.Net.WebRequest.Create(address);
            System.Net.WebResponse webRes = webReq.GetResponse();
            System.IO.Stream mystream = webRes.GetResponseStream();
            if (mystream == null) return false;

            HtmlAgilityPack.HtmlDocument myHtmlDoc = new HtmlAgilityPack.HtmlDocument();
            myHtmlDoc.Load(mystream);

            List<String> row = new List<string>();
            try
            {
                //string xpathGoldTable = "//*[@id='main_container']/tr[1]/td[1]/div[3]/div[2]/table/";
                string xpathGoldTable = "//*[@id='hnxidx']";
                var askNode = myHtmlDoc.DocumentNode.SelectSingleNode(xpathGoldTable);
                hastcIdx.Value = decimal.Parse(askNode.InnerText, dataCulture);
                //code
                row.Add("XAUUSD");
                //Bid/Ask
                //string xpathGoldTable

                if (askNode != null)
                    row.Add(askNode.InnerText.Trim());
            }
            catch (System.Exception ex)
            {
                return false;
            }

            return retVal;
        }
Example #5
0
        public static List<MarketData> FillByPivotData(MarketData pivotData, List<MarketData> inputData)
        {
            // pivotData의 datetime에 맞추어서 나머지 데이터를 채운다.
            DateTime curDateTime = pivotData.StartDate;
            List<MarketData> outputData = new List<MarketData>();
            Dictionary<String, MarketDataTrace> trace = new Dictionary<string, MarketDataTrace>();

            // init variables
            foreach (MarketData md in inputData)
            {
                String ticker = md.Ticker;
                DOHLC firstData = md.GetByIndex(0);
                trace.Add(md.Ticker, new MarketDataTrace(ticker, firstData));
                outputData.Add(new MarketData(md));
            }

            while (curDateTime <= pivotData.EndDate)
            {
                if (pivotData.IsExistDate(curDateTime))
                {
                    // update trace
                    foreach (MarketData md in inputData)
                    {
                        String ticker = md.Ticker;
                        if (md.IsExistDate(curDateTime))
                        {
                            trace[ticker].CurData = md.GetData(curDateTime);
                        }
                    }

                    // set data
                    foreach (MarketData md in outputData)
                    {
                        String ticker = md.Ticker;
                        MarketDataTrace tr = trace[ticker];
                        // 기준 데이터보다 전 데이터이어야 한다.
                        Trace.Assert(tr.CurData.CurDate <= curDateTime, String.Format("{0}, {1}, {2}", tr.Ticker, tr.CurData.CurDate, curDateTime));
                        md.AddDatum(curDateTime, tr.CurData.OHLC);

                        if (tr.CurData.CurDate != curDateTime)
                        {
                            md.SetPrevDataUsedDate(curDateTime);
                        }
                    }
                }
                curDateTime = curDateTime.AddDays(1);
            }
            return outputData;
        }
Example #6
0
        public static void TransferData(MarketData marketData)
        {
            var context = new MySqlContext();

            TransferTowns(marketData.Towns, context);
            TransferSupermarkets(marketData.Supermarkets, context);
            TransferProductsTypes(marketData.ProductsTypes, context);
            TransferVendors(marketData.Vendors, context);
            TransferMeasures(marketData.Measures, context);
            TransferProducts(marketData.Products, context);
            TransferSalesReports(marketData.SalesReports, context);
            TransferVendorExpenses(marketData.VendorExpenses, context);

            context.SaveChanges();
        }
        public async Task<IList<IMarketData>> GetMarkets()
        {
            var list = new List<IMarketData>();

            var @params = new Dictionary<string, string>
            {
                {"method", "marketdatav2"}
            };

            var data = await Request(PublicApiBase, PublicApiEndpoint, @params);

            try
            {
                foreach (var kvp in [email protected])
                {
                    try
                    {
                        var buyOrders = (IList<dynamic>) kvp.Value.buyorders;
                        var sellOrders = (IList<dynamic>) kvp.Value.sellorders;

                        var entry = new MarketData
                        {
                            Exchange = Exchange.Cryptsy,
                            MarketCurrency = kvp.Value.primarycode.ToUpperInvariant(),
                            BaseCurrency = kvp.Value.secondarycode.ToUpperInvariant(),
                            Ask = double.Parse(sellOrders.First().price, CultureInfo.InvariantCulture),
                            Bid = double.Parse(buyOrders.First().price, CultureInfo.InvariantCulture),
                            VolumeInMarketCurrency = double.Parse(kvp.Value.volume, CultureInfo.InvariantCulture),
                        };
                        list.Add(entry);
                    }
                    catch (ArgumentNullException)
                    { } // just skip the exception that occurs when a field can not be read.
                    catch (Exception e)
                    {
                        _logger.Error(e.Message);
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Error(e.Message);
            }

            return list;
        }
        public async Task<IList<IMarketData>> GetMarkets()
        {
            var list = new List<IMarketData>();

            var @params = new Dictionary<string, string>
            {
                {"command", "returnTicker"}
            };

            var data = await Request(ApiBase, PublicApiEndpoint, @params);

            try
            {
                foreach (var kvp in data)
                {
                    try
                    {
                        string name = kvp.Key;
                        var temp = name.Split('_');

                        var entry = new MarketData
                        {
                            Exchange = Exchange.Poloniex,
                            MarketCurrency = temp.Last().ToUpperInvariant(),
                            BaseCurrency = temp.First().ToUpperInvariant(),
                            Ask = double.Parse(kvp.Value.lowestAsk, CultureInfo.InvariantCulture),
                            Bid = double.Parse(kvp.Value.highestBid, CultureInfo.InvariantCulture),
                            VolumeInMarketCurrency = double.Parse(kvp.Value.quoteVolume, CultureInfo.InvariantCulture),
                            VolumeInBaseCurrency = double.Parse(kvp.Value.baseVolume, CultureInfo.InvariantCulture),
                        };

                        list.Add(entry);
                    }
                    catch (Exception e)
                    {
                        _logger.Error(e.Message);
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Error(e.Message);
            }

            return list;
        }
        public async Task<IList<IMarketData>> GetMarkets()
        {
            var list = new List<IMarketData>();
            var data = await Request(ApiBase, "public/getmarketsummaries");

            try
            {
                foreach (var market in data.@result)
                {
                    try
                    {
                        string name = market.MarketName;
                        var temp = name.Split('-');

                        var entry = new MarketData
                        {
                            Exchange = Exchange.Bittrex,
                            MarketCurrency = temp.Last().ToUpperInvariant(),
                            BaseCurrency = temp.First().ToUpperInvariant(),
                            Ask = market.Ask,
                            Bid = market.Bid,
                            VolumeInMarketCurrency = market.Volume,
                            VolumeInBaseCurrency = market.BaseVolume
                        };

                        list.Add(entry);
                    }
                    catch (RuntimeBinderException)
                    { } // just skip the exception that occurs when a field can not be read.
                    catch (Exception e)
                    {
                        _logger.Error(e.Message);
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Error(e.Message);
            }

            return list;
        }
Example #10
0
        protected virtual bool GetData(databases.baseDS.exchangeDetailRow exchangeDetailRow, ref MarketData vnIdx, ref MarketData vn30Idx)
        {
            CultureInfo dataCulture = common.language.GetCulture("en-US");
            //Hose
            clientHOSE.HoSTC_ServiceSoapClient client = new Imports.clientHOSE.HoSTC_ServiceSoapClient();
            client.Endpoint.Address = new System.ServiceModel.EndpointAddress(exchangeDetailRow.address);

            System.ServiceModel.BasicHttpBinding binding = (client.Endpoint.Binding as System.ServiceModel.BasicHttpBinding);

            binding.OpenTimeout = TimeSpan.FromSeconds(Consts.constWebServiceTimeOutInSecs);
            binding.CloseTimeout = binding.OpenTimeout;
            binding.SendTimeout = binding.OpenTimeout;

            binding.MaxReceivedMessageSize = Consts.constWebServiceMaxReceivedMessageSize;
            binding.MaxBufferSize = Consts.constWebServiceMaxReceivedMessageSize;

            binding.ReaderQuotas.MaxStringContentLength = Consts.constWebServiceMaxStringContentLength;
            binding.ReaderQuotas.MaxBytesPerRead = Consts.constWebServiceMaxBytesPerRead;

            string[] arr = client.GetLiveTotalMKT().Split('*');
            string content = string.Empty;
            List<string> rows = new List<string>();
            foreach (var item in arr)
            {
                if (item.Trim() == "") continue;
                rows.Add(item);
                content += item + Environment.NewLine;
            }
            string[] dRow = rows[8].Split('|');

            vnIdx.Value = decimal.Parse(dRow[0], dataCulture);
            vnIdx.TotalQty = decimal.Parse(dRow[4], dataCulture);
            vnIdx.TotalAmt = decimal.Parse(dRow[5], dataCulture);

            vn30Idx.Value = decimal.Parse(dRow[10], dataCulture);
            vn30Idx.TotalQty = 0;
            vn30Idx.TotalAmt = 0;

            return true;
        }
        SinglePnLResult SingleSimulate(MarketData md)
        {
            List<RawTradingData> tradingList = new List<RawTradingData>();
            MarketDataSetKey key= (DataUtil.GetMarketDataKeyFromTicker(md.Ticker));
            DateTime curDate = _startDate;
            int index = 0;
            double curSize = 0;
            while (curDate <= _endDate)
            {

                if (md.IsExistDate(curDate))
                {
                    double curPrice = md.GetData(curDate).OHLC.Close;
                    if (index % _rebalancingPeriod == 0)
                    {
                        curSize = _baseInvest / curPrice;
                    }

                    if (curPrice < 50000)
                    {
                        curSize = Math.Round(curSize / 10, 0) * 10;
                    }

                    RawTradingData tradingData = new RawTradingData(key, curDate, curPrice, curSize);
                    tradingData.AddDelta(curSize * curPrice / _baseInvest);
                    tradingList.Add(tradingData);
                    index++;
                }
                curDate = curDate.AddDays(1);
            }

            SinglePnLResult profitAndLossResult =
                new SinglePnLResult(key, key.ToString(), TradingDirection.Long, true, tradingList);
            profitAndLossResult.CalculatePnL();

            return profitAndLossResult;
        }
Example #12
0
 public OrderData(string[] raw_pieces, MarketData market_data)
 {
     try
     {
         this.label = raw_pieces[0].Trim();
         this.symbol = market_data.GetSymbol(raw_pieces[1].Trim());
         this.setType(Convert.ToInt32(raw_pieces[2].Trim()));
         this.lot = Convert.ToInt64(this.parseDouble(raw_pieces[3]) * mt_lot_coefficient);
         double price = this.parseDouble(raw_pieces[4]);
         this.sl = this.getPipDistance(price, this.parseDouble(raw_pieces[5]));
         this.tp = this.getPipDistance(price, this.parseDouble(raw_pieces[6]));
     } catch (Exception e)
     {
         this.initialized_properly = false;
     }
 }
Example #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SMART.Generators.RandomMarketGenerator"/> class.
 /// </summary>
 public RandomMarketGenerator(MarketData marketData)
     : base(marketData)
 {
 }
 private Symbol GetSymbol(Position position)
 {
     return(MarketData.GetSymbol(position.SymbolCode));
 }
 internal static HandleRef getCPtr(MarketData obj)
 {
     return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
 }
Example #16
0
 internal static HandleRef getCPtr(MarketData obj)
 {
     return((obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr);
 }
        private void calibration_market_quote_sensitivity_check(System.Func <MarketData, RatesProvider> calibrator, RatesCurveGroupDefinition config, double shift, MarketData ts)
        {
            double                         notional = 100_000_000.0;
            double                         rate     = 0.0400;
            SwapTrade                      trade    = FixedIborSwapConventions.USD_FIXED_1Y_LIBOR_3M.createTrade(VAL_DATE_BD, Period.ofMonths(6), Tenor.TENOR_7Y, BuySell.BUY, notional, rate, REF_DATA);
            RatesProvider                  result   = CALIBRATOR.calibrate(config, ALL_QUOTES_BD.combinedWith(ts), REF_DATA);
            ResolvedSwap                   product  = trade.Product.resolve(REF_DATA);
            PointSensitivityBuilder        pts      = SWAP_PRICER.presentValueSensitivity(product, result);
            CurrencyParameterSensitivities ps       = result.parameterSensitivity(pts.build());
            CurrencyParameterSensitivities mqs      = MQC.sensitivity(ps, result);
            double                         pv0      = SWAP_PRICER.presentValue(product, result).getAmount(USD).Amount;

            double[] mqsDscComputed = mqs.getSensitivity(DSCON_CURVE_NAME, USD).Sensitivity.toArray();
            for (int i = 0; i < DSC_NB_NODES; i++)
            {
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Map<com.opengamma.strata.data.MarketDataId<?>, Object> map = new java.util.HashMap<>(ALL_QUOTES_BD.getValues());
                IDictionary <MarketDataId <object>, object> map = new Dictionary <MarketDataId <object>, object>(ALL_QUOTES_BD.Values);
                map[QuoteId.of(StandardId.of(SCHEME, DSC_ID_VALUE[i]))] = DSC_MARKET_QUOTES[i] + shift;
                ImmutableMarketData marketData = ImmutableMarketData.of(VAL_DATE_BD, map);
                RatesProvider       rpShifted  = calibrator(marketData.combinedWith(ts));
                double pvS = SWAP_PRICER.presentValue(product, rpShifted).getAmount(USD).Amount;
                assertEquals(mqsDscComputed[i], (pvS - pv0) / shift, TOLERANCE_PV_DELTA);
            }
            double[] mqsFwd3Computed = mqs.getSensitivity(FWD3_CURVE_NAME, USD).Sensitivity.toArray();
            for (int i = 0; i < FWD3_NB_NODES; i++)
            {
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Map<com.opengamma.strata.data.MarketDataId<?>, Object> map = new java.util.HashMap<>(ALL_QUOTES_BD.getValues());
                IDictionary <MarketDataId <object>, object> map = new Dictionary <MarketDataId <object>, object>(ALL_QUOTES_BD.Values);
                map[QuoteId.of(StandardId.of(SCHEME, FWD3_ID_VALUE[i]))] = FWD3_MARKET_QUOTES[i] + shift;
                ImmutableMarketData marketData = ImmutableMarketData.of(VAL_DATE_BD, map);
                RatesProvider       rpShifted  = calibrator(marketData.combinedWith(ts));
                double pvS = SWAP_PRICER.presentValue(product, rpShifted).getAmount(USD).Amount;
                assertEquals(mqsFwd3Computed[i], (pvS - pv0) / shift, TOLERANCE_PV_DELTA);
            }
        }
        private EquityMarketDataManager()
        {
            _mdPivot = DataUtil.GetKeyMarketData(
                MarketDataSetKey.KospiFuture, EquityVolPredefinedVariables.ReadStartDate, EquityVolPredefinedVariables.ReadEndDate);
            if (EquityVolPredefinedVariables.BUseDB)
            {
                LoadEquityPriceDataFromDB();
            }
            else
            {
                LoadEquityPriceDataFromText();
                LoadMarketCapData();
            }

            InitSectorEquityMapping();
        }
 MarketData ReadPivotMarketData(DateTime startDate, DateTime endDate)
 {
     MarketData md = new MarketData(startDate, endDate, _mdPivot.Ticker);
     DateTime curDate = startDate;
     while (curDate <= endDate)
     {
         if (_mdPivot.IsExistDate(curDate))
         {
             DOHLC dohlc = _mdPivot.GetData(curDate);
             md.AddDatum(dohlc);
         }
         curDate = curDate.AddDays(1);
     }
     return md;
 }
        public void ReadyData()
        {
            // Load data
            MarketData mdKospi = new MarketData(Input.StartDate, Input.EndDate, "KM1 R:00_0_R Index");
            MarketData mdBond = new MarketData(Input.StartDate, Input.EndDate, "KE1 R:00_0_R Comdty");
            MarketData mdDollar = new MarketData(Input.StartDate, Input.EndDate, "KU1 R:00_0_R Curncy");
            mdKospi.LoadDataFromDB();
            mdBond.LoadDataFromDB();
            mdDollar.LoadDataFromDB();

            // Ready data
            List<MarketData> l = new List<MarketData>();
            l.Add(mdKospi);
            l.Add(mdBond);
            l.Add(mdDollar);
            List<MarketData> alignedData = DataUtil.FillByPivotData(mdKospi, l);
            Boolean arranged = DataUtil.IsArrangedDateAndIndex(alignedData);
            Trace.Assert(arranged);

            //Set data
            this._readyData.Add(MarketDataSetKey.KospiFuture, alignedData[0]);
            this._readyData.Add(MarketDataSetKey.KtbFuture, alignedData[1]);
            this._readyData.Add(MarketDataSetKey.DollarFuture, alignedData[2]);
            this._readyData.RegisterPivotData(alignedData[0]);
        }
Example #21
0
        public override void onTick(MarketData md)
        {
            Console.WriteLine(" Got tick for symbol "+md.getInstrument().getInstrumentName());

            if(_data.isOrderPending)
            {
                Console.WriteLine("Orders are pending no need to react on this tick.");
                return ;
            }
            else
            {
                Console.WriteLine("md.getInstrument().getInstrumentName() "+md.getInstrument().getInstrumentName());
                if(md.getInstrument().getInstrumentName() == (_data.firstLegSymbol))
                {
                    getAveragePrice(md, _data.qty, _data.firstLegSide, 1);
                    Console.WriteLine("First leg avg price : %d\n", _data.avgPriceSecondLeg);
                }
                else if( md.getInstrument().getInstrumentName() == (_data.secondLegSymbol))
                {
                    getAveragePrice(md, _data.qty, _data.secondLegSide, 2);
                    Console.WriteLine("Second leg avg price : %d\n", _data.avgPriceFirstLeg);
                }
                else
                {
                    Console.WriteLine("Unknown symbol tick.");
                }
            }

            if(_data.avgPriceSecondLeg == 0)
            {
              // leg-2 is empty if bid is placed cancel our bib.
              if(_data.bidPlaced)
              {
                    cancelFirstLeg();
               }
               }
               else
               {
              _data.orderPriceFirstLeg =
                (_data.minProfit * _data.firstLegMode) +
                  _data.avgPriceSecondLeg;

              if(!_data.bidPlaced)
              {
                    firstLegBid();
                    _data.bidPlaced = true;
                    _data.isOrderPending = true;
              }
              else if(_data.bidPlaced &&
                      _data.firstLegOrder.getOrderStatus() == OrderStatus.OrderStatus_PENDING &&
                      _data.lastBidPrice != _data.orderPriceFirstLeg)
              {
                    modifyOrder();
                    _data.isOrderPending = true;
              }
              else
              {
                    Console.WriteLine("Bid update is not needed.");
              }
            }
        }
Example #22
0
 static bool Get_IDX_HASTC(string address, ref MarketData hastcIdx)
 {
     bool retVal = true;
     CultureInfo dataCulture = common.language.GetCulture("en-US");
     HttpWebRequest wRequest = HttpWebRequest.Create(new Uri(address)) as HttpWebRequest;
     HttpWebResponse wResponse = wRequest.GetResponse() as HttpWebResponse;
     StreamReader reader = new StreamReader(wResponse.GetResponseStream());
     string htmlContent = reader.ReadToEnd();
     HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
     doc.LoadHtml(htmlContent);
     HtmlAgilityPack.HtmlNode nodeHNXIndex = doc.GetElementbyId("IDX");
     HtmlAgilityPack.HtmlNode nodeTongKL = doc.GetElementbyId("QTY");
     if (nodeHNXIndex!=null)
          hastcIdx.Value = decimal.Parse(nodeHNXIndex.InnerHtml, dataCulture);
     else retVal = false;
     if (nodeTongKL != null) hastcIdx.TotalQty = decimal.Parse(nodeTongKL.InnerHtml, dataCulture);
     else retVal = false;
     hastcIdx.TotalAmt = 0;
     return retVal;
 }
Example #23
0
        void CreateHedgingTradingData(MarketData md)
        {
            int curPositionSize = 0;
            double curGrossDelta = 0;
            double curHedgingFactor = EquityVolPredefinedVariables.FullHedgingFactor;
            double prevHedgingFactor = 0;
            double prevPrice = 0;
            int lastHedgedIndex = 0;
            for (int index = 0; index < md.GetTotalCount(); index++)
            {
                bool bHegingTest = false;
                DOHLC dohlc = md.GetByIndex(index);

                DateTime curDate = dohlc.CurDate;

                if (curDate.DayOfWeek  == DayOfWeek.Saturday
                    || curDate.DayOfWeek == DayOfWeek.Sunday)
                {
                    continue;
                }

                double curPrice = dohlc.OHLC.Close;
                if (prevPrice != 0 && curPrice != 0)
                {
                    double upDownRate = MathUtil.GetUpDownRate(prevPrice, curPrice);
                    if (_upDownRates.Count == _volN)
                    {
                        _upDownRates.Dequeue();
                    }
                    _upDownRates.Enqueue(upDownRate);
                }

                if (_bMATrendTester)
                {
                    _leadingMA.Add(curPrice);
                    _baseMA.Add(curPrice);

                    //if(prevHedgingFactor == EquityVolPredefinedVariables.OverHedgingFactor
                    //    && MathUtil.GetUpDownRate(_nonNeutralHedgingEntryPrice, prevPrice) > 0.02)
                    //{
                    //    curHedgingFactor = EquityVolPredefinedVariables.FullHedgingFactor;
                    //}
                    //if (prevHedgingFactor == EquityVolPredefinedVariables.UnderHedgingFactor
                    //    && MathUtil.GetUpDownRate(_nonNeutralHedgingEntryPrice, prevPrice) < -0.02)
                    //{
                    //    curHedgingFactor = EquityVolPredefinedVariables.FullHedgingFactor;
                    //}

                    if (MathUtil.GetUpDownRate(prevPrice, curPrice) > -0.02)
                    {
                        curHedgingFactor = GetCurTrendHedgingFactor();
                    }

                    //bHegingTest = (curHedgingFactor != prevHedgingFactor) ||
                    //     ((lastHedgedIndex + (int)(EquityVolPredefinedVariables.RebalancingPeriod / 2) <= index)
                    //         && index % (_hedingInterval) == 0);
                    bHegingTest = (curHedgingFactor != prevHedgingFactor) ||
                        (index % (_hedingInterval) == 0 && (lastHedgedIndex + (2 * _hedingInterval) <= index));
                    //bHegingTest = (curHedgingFactor != prevHedgingFactor);
                    //bHegingTest = (curHedgingFactor != prevHedgingFactor) ||
                    //   (lastHedgedIndex + (int)(EquityVolPredefinedVariables.RebalancingPeriod / 2) <= index);
                }
                else
                {
                    bHegingTest = index % (2 * _hedingInterval) == 0;
                }

                if (bHegingTest)
                {
                    if (_grossDeltas == null)
                    {
                        curGrossDelta = curHedgingFactor * 1.0;
                        curPositionSize = GetGHedgingPositonSize(curGrossDelta, curPrice, _baseInvest);
                        prevHedgingFactor = curHedgingFactor;
                        lastHedgedIndex = index;
                    }
                    else if (_grossDeltas.ContainsKey(curDate))
                    {
                        curGrossDelta = curHedgingFactor * _grossDeltas[curDate];
                        curPositionSize = GetGHedgingPositonSize(curGrossDelta, curPrice, _baseInvest);
                        prevHedgingFactor = curHedgingFactor;
                        lastHedgedIndex = index;
                    }
                }
                if (curDate >= _startDate)
                {
                    RawTradingData tradingData =
                        new RawTradingData(MarketDataSetKey.KospiFuture, curDate, curPrice, curPositionSize);
                    tradingData.AddDelta(curGrossDelta);
                    _tradingDataList.Add(tradingData);
                }
                prevPrice = curPrice;
            }
        }
Example #24
0
 public List<RawTradingData> GetGrossHedgeTradingData(MarketData md)
 {
     CreateHedgingTradingData(md);
     return _tradingDataList;
 }
Example #25
0
 public void SendMarketDataEvent(MarketData marketData)
 {
     _marketDataSender.SendEvent(marketData);
 }
 public virtual void UpdateMarketData(MarketData marketData)
 {
     throw new Exception("Not implement method");
 }
Example #27
0
 public void RegisterPivotData(MarketData md)
 {
     this.PivotData = md;
 }
        //-------------------------------------------------------------------------
        /// <summary>
        /// Calibrates a single curve group, containing one or more curves.
        /// <para>
        /// The calibration is defined using <seealso cref="RatesCurveGroupDefinition"/>.
        /// Observable market data, time-series and FX are also needed to complete the calibration.
        /// The valuation date is defined by the market data.
        /// </para>
        /// <para>
        /// The Jacobian matrices are computed and stored in curve metadata.
        ///
        /// </para>
        /// </summary>
        /// <param name="curveGroupDefn">  the curve group definition </param>
        /// <param name="marketData">  the market data required to build a trade for the instrument, including time-series </param>
        /// <param name="refData">  the reference data, used to resolve the trades </param>
        /// <returns> the rates provider resulting from the calibration </returns>
        public ImmutableRatesProvider calibrate(RatesCurveGroupDefinition curveGroupDefn, MarketData marketData, ReferenceData refData)
        {
//JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter:
            IDictionary <Index, LocalDateDoubleTimeSeries> timeSeries = marketData.TimeSeriesIds.Where(typeof(IndexQuoteId).isInstance).Select(typeof(IndexQuoteId).cast).collect(toImmutableMap(id => id.Index, id => marketData.getTimeSeries(id)));
            ImmutableRatesProvider knownData = ImmutableRatesProvider.builder(marketData.ValuationDate).fxRateProvider(MarketDataFxRateProvider.of(marketData)).timeSeries(timeSeries).build();

            return(calibrate(ImmutableList.of(curveGroupDefn), knownData, marketData, refData));
        }
Example #29
0
        TriState _ModifyPosition(double magicIndex, string symbolCode, int slAction, double slValue, int tpAction, double tpValue)
        {
            Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);
            var    pos    = Positions.Find("FxProQuant_" + magicIndex.ToString("F0"), symbol);

            if (pos == null)
            {
                return(new TriState());
            }
            double?sl, tp;

            if (slValue == 0)
            {
                sl = null;
            }
            else
            {
                switch (slAction)
                {
                case 0:
                    sl = pos.StopLoss;
                    break;

                case 1:
                    if (pos.TradeType == TradeType.Buy)
                    {
                        sl = pos.EntryPrice - slValue * symbol.TickSize;
                    }
                    else
                    {
                        sl = pos.EntryPrice + slValue * symbol.TickSize;
                    }
                    break;

                case 2:
                    sl = slValue;
                    break;

                default:
                    sl = pos.StopLoss;
                    break;
                }
            }
            if (tpValue == 0)
            {
                tp = null;
            }
            else
            {
                switch (tpAction)
                {
                case 0:
                    tp = pos.TakeProfit;
                    break;

                case 1:
                    if (pos.TradeType == TradeType.Buy)
                    {
                        tp = pos.EntryPrice + tpValue * symbol.TickSize;
                    }
                    else
                    {
                        tp = pos.EntryPrice - tpValue * symbol.TickSize;
                    }
                    break;

                case 2:
                    tp = tpValue;
                    break;

                default:
                    tp = pos.TakeProfit;
                    break;
                }
            }
            if (!ModifyPosition(pos, sl, tp).IsSuccessful)
            {
                Thread.Sleep(400);
                return(false);
            }
            return(true);
        }
        void CreateTradingData(MarketData md)
        {
            int curPositionSize = 0;
            double curFactor = 0;
            double entryPrice = 0;
            for (int index = 0; index < md.GetTotalCount(); index++)
            {
                double prevFactor = curFactor;
                DOHLC dohlc = md.GetByIndex(index);
                DateTime curDate = dohlc.CurDate;
                double curPrice = dohlc.OHLC.Close;
                if (_bMATrendTester)
                {
                    _leadingMA.Add(curPrice);
                    _baseMA.Add(curPrice);
                }
                double curLeadingMA = _leadingMA.GetCurMA();
                double curBaseMA = _baseMA.GetCurMA();

                //curFactor = GetTradingFactorWith3Value(curPrice, curLeadingMA, curBaseMA, curFactor, entryPrice);
                curFactor = GetMASpreadSwitchedTradingFactor(curPrice, curLeadingMA, curBaseMA, curFactor);
                //curFactor = GetMASpreadTradingFactor(maSpread, curFactor);

                if (!IsAvailableTimeRange(curDate, curFactor))
                {
                    curFactor = kNeutralFactor;
                    //AddMATrendTester(10, 50);
                }

                //if (TestLossCut(prevFactor, entryPrice, curPrice))
                //{
                //    curFactor = kNeutralFactor;
                //}

                curPositionSize = (int) curFactor;

                if (prevFactor == kNeutralFactor && curFactor != kNeutralFactor)
                {
                    entryPrice = curPrice;
                }

                if (prevFactor < curFactor)
                {
                    curPrice = curPrice + 0.025;
                }
                else if (prevFactor > curFactor)
                {
                    curPrice = curPrice - 0.025;
                }

                RawTradingData tradingData =
                    new RawTradingData(MarketDataSetKey.KospiFuture, curDate, curPrice, curPositionSize);
                _tradingDataList.Add(tradingData);

            }
        }
Example #31
0
        public void InitilizeGridMarket()
        {
            //Initilize new market servers
            MarketServers = new CrossServer(Config.MarketPort, this);
            //Attempt to create market servers!
            if (MarketServers.CreateServers() == false)
            {
                Hangar.Debug("Unable to start market servers! Check logs & contact plugin dev!");
                Config.GridMarketEnabled = false;
            }



            Config.HostServer = IsHostServer;


            ServerOffersDir     = Path.Combine(_StoragePath, "HangarServerOffers");
            ServerMarketFileDir = Path.Combine(ServerOffersDir, "HangarServerOffers.json");
            Directory.CreateDirectory(ServerOffersDir);
            MarketData PublicData = new MarketData();


            if (File.Exists(ServerMarketFileDir))
            {
                using (StreamReader file = File.OpenText(ServerMarketFileDir))
                {
                    JsonSerializer serializer = new JsonSerializer();
                    PublicData = (MarketData)serializer.Deserialize(file, typeof(MarketData));
                }
            }

            if (IsHostServer)
            {
                MarketData Data               = new MarketData();
                Accounts   Accounts           = new Accounts();
                string     MarketPath         = Path.Combine(Config.FolderDirectory, "Market.json");
                string     PlayerAccountsPath = Path.Combine(Config.FolderDirectory, "PlayerAccounts.json");


                //Initilize loading of files!
                if (File.Exists(MarketPath))
                {
                    using (StreamReader file = File.OpenText(MarketPath))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        Data = (MarketData)serializer.Deserialize(file, typeof(MarketData));
                    }
                }


                if (File.Exists(PlayerAccountsPath))
                {
                    using (StreamReader file = File.OpenText(PlayerAccountsPath))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        Accounts = (Accounts)serializer.Deserialize(file, typeof(Accounts));
                    }
                }


                //GridDefinition = Data.GridDefinition;
                PublicOfferseGridList = PublicData.List;
                GridList       = Data.List;
                PlayerAccounts = Accounts.PlayerAccounts;
            }
            else
            {
                Hangar.Debug("Requesting update!");

                //Client start. (Tell server to broadcast to all clients!)
                CrossServerMessage SendMessage = new CrossServerMessage();
                SendMessage.Type = CrossServer.MessageType.RequestAll;

                MarketServers.Update(SendMessage);
                Hangar.Debug("Initial Send Request");
            }
        }
Example #32
0
 public ResolvedSwapTrade resolvedTrade(double quantity, MarketData marketData, ReferenceData refData)
 {
     return(trade(quantity, marketData, refData).resolve(refData));
 }
Example #33
0
 /// <summary>
 /// Markets the tick.
 /// </summary>
 public virtual void MarketTick(long tick, MarketData marketData)
 {
     if (_sellSignal(tick, marketData))
     {
     }
 }
Example #34
0
 protected virtual void AddImportRow(DateTime updateTime, MarketData marketValue, bool isTotalVolume, databases.importDS.importPriceDataTable tbl)
 {
     databases.importDS.importPriceRow oldImportRow;
     databases.importDS.importPriceRow importRow = tbl.NewimportPriceRow();
     databases.AppLibs.InitData(importRow);
     importRow.isTotalVolume = isTotalVolume;
     importRow.onDate = updateTime;
     importRow.stockCode = marketValue.Code;
     importRow.volume = marketValue.TotalQty;
     importRow.closePrice = marketValue.Value;
     
     //Only add new when there are some changes 
     oldImportRow = lastImportData.Find(importRow);
     if (!lastImportData.IsSameData(importRow, oldImportRow))
     {
         tbl.AddimportPriceRow(importRow);
         lastImportData.Update(importRow);
     }
     else importRow.CancelEdit();
 }
        void LoadEquityPriceDataFromDB()
        {
            foreach (string keyString in Enum.GetNames(typeof(KospiEquityDataKey)))
            {
                MarketDataSetKey key = (MarketDataSetKey)Enum.Parse(typeof(MarketDataSetKey), keyString, true);
                try
                {
                    MarketData dbMarketData = DataUtil.GetKeyMarketData(
                        key, EquityVolPredefinedVariables.ReadStartDate, EquityVolPredefinedVariables.ReadEndDate);
                    if (dbMarketData.GetTotalCount() == 0)
                    {
                        continue;
                    }

                    DateTime readStartDate = dbMarketData.GetByIndex(0).CurDate;
                    DateTime readEndDate = dbMarketData.GetByIndex((int)dbMarketData.GetTotalCount() - 1).CurDate;
                    string ticker = DataUtil.GetTickerFromMarketDataKey(key);

                    MarketData md = new MarketData(readStartDate, readEndDate, ticker);
                    for (int i = 0; i < dbMarketData.GetTotalCount(); i++)
                    {
                        DOHLC dohlc = dbMarketData.GetByIndex(i);
                        DateTime curDate = dohlc.CurDate;
                        if (curDate.DayOfWeek == DayOfWeek.Saturday
                            || curDate.DayOfWeek == DayOfWeek.Sunday)
                        {
                            continue;
                        }
                        md.AddDatum(dohlc);
                    }

                    MarketData mdKospi = ReadPivotMarketData(md.StartDate, md.EndDate);
                    List<MarketData> output =
                        DataUtil.FillByPivotData(mdKospi, new List<MarketData> { md });
                    _priceData.Add(key, output[0]);
                }
                catch (Exception ex)
                {
                    logger.Warn(ex.ToString());
                }
            }
        }
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(MarketData obj) {
   return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SMART.Generators.RandomMarketGenerator"/> class.
 /// </summary>
 public RandomMarketGenerator(MarketData marketData)
     : base(marketData)
 {
 }
Example #38
0
        protected override void OnBar()
        {
            if (!TradingEnabled)
            {
                return;
            }

            // Check the Day of Week for Trading....
            bool OkToTradeToday = false;

            foreach (string DOW in ValidDays.Split(','))
            {
                if (MarketSeries.OpenTime.LastValue.DayOfWeek.ToString().ToLower().Contains(DOW.ToLower()))
                {
                    OkToTradeToday = true;
                }
            }

            if (!OkToTradeToday)
            {
                return;
            }



            // Check that the last Bar was the Open.
            if (MarketSeries.OpenTime.Last(1).TimeOfDay == new TimeSpan(SignalBarHour, SignalBarMinute, 0))
            {
                double BarLength = GetBarLength(1);

                MarketSeries     MarketSeriesDaily = MarketData.GetSeries(TimeFrame.Daily);
                AverageTrueRange ATR = Indicators.AverageTrueRange(MarketSeriesDaily, 5, MovingAverageType.Simple);

                if (ATR.Result.LastValue >= MinATR)
                {
                    if (GetBarDirection(1) != "NEUTRAL")
                    {
                        TradeType Trade;
                        double    Entry;
                        double    SL;
                        double    TP        = BarLength * (1 / Symbol.TickSize);
                        long      Contracts = GetContractSize();

                        if (GetBarDirection(1) == "DOWN")
                        {
                            Trade = TradeType.Sell;
                            Entry = MarketSeries.Low.Last(1) - BarBreakPointSize;
                            SL    = (MarketSeries.High.Last(1) + BarBreakPointSize) - Entry;

                            //Increasing the SL a little more
                            SL = SL + 8;
                        }
                        else
                        {
                            Trade = TradeType.Buy;
                            Entry = MarketSeries.High.Last(1) + BarBreakPointSize;
                            SL    = Entry - (MarketSeries.Low.Last(1) - BarBreakPointSize);

                            //Increasing the SL a little more
                            SL = SL + 8;
                        }

                        SL = SL * (1 / Symbol.TickSize);

                        var Result = PlaceStopOrder(Trade, Symbol, Contracts, Entry, "BarBreak", SL, TP, MarketSeries.OpenTime.LastValue.AddMinutes(MaxMinuteValid));

                        if (Result.IsSuccessful)
                        {
                            string OrderPlacedSummary = "Order Placed! BarLength: " + BarLength.ToString() + ", " + Trade.ToString() + ": " + Symbol.Code.ToString() + ", Entry: " + Entry.ToString() + ", Stop: " + SL.ToString() + ", TakeProfit: " + TP.ToString();
                            Print(OrderPlacedSummary);
                            Notifications.SendEmail("*****@*****.**", "*****@*****.**", "New Position Opened", OrderPlacedSummary);
                        }
                        else
                        {
                            Print("Error: " + Result.Error);
                        }
                    }
                }
                else
                {
                    Print("5 Day ATR (" + ATR.Result.LastValue.ToString() + ") was outside acceptable boundaries.");
                }
            }
        }
Example #39
0
 public bool ShouldBuy(MarketData data)
 => DateSystem.IsPublicHoliday(data.Date.AddDays(1), CountryCode.AU) ||
 DateSystem.IsPublicHoliday(data.Date.AddDays(1), CountryCode.US) ||
 DateSystem.IsPublicHoliday(data.Date.AddDays(1), CountryCode.CN);
        /// <summary>
        /// calculates the min, max and average market price for supply and demand of each commodity
        /// </summary>
        /// <returns></returns>
        public Dictionary<int, MarketData> calculateAveragePrices()
        {
            MarketData CommodityData;
            Dictionary<int, MarketData> collectedData = new Dictionary<int, MarketData>();

            foreach (EDStation Station in m_Stations[(int)(enDataType.Data_Merged)])
            {
                if (Station.Listings != null)
                    foreach (Listing StationCommodity in Station.Listings)
                    {
                        if (!collectedData.TryGetValue(StationCommodity.CommodityId, out CommodityData))
                        {
                            // add a new Marketdata-Object
                            CommodityData = new MarketData();
                            CommodityData.Id        = StationCommodity.CommodityId;
                            collectedData.Add(CommodityData.Id, CommodityData);

                        }

                        if (StationCommodity.Demand != 0)
                        { 
                            if (StationCommodity.BuyPrice > 0)
                                CommodityData.BuyPrices_Demand.Add(StationCommodity.BuyPrice);

                            if (StationCommodity.SellPrice > 0)
                                CommodityData.SellPrices_Demand.Add(StationCommodity.SellPrice);
                        
                        }

                        if (StationCommodity.Supply != 0)
                        { 
                            if (StationCommodity.BuyPrice > 0)
                                CommodityData.BuyPrices_Supply.Add(StationCommodity.BuyPrice);

                            if (StationCommodity.SellPrice > 0)
                                CommodityData.SellPrices_Supply.Add(StationCommodity.SellPrice);
                        
                        }
                    }        
            }

            return collectedData;
        }
        /// <summary>
        /// Calibrates a list of curve groups, each containing one or more curves.
        /// <para>
        /// The calibration is defined using a list of <seealso cref="RatesCurveGroupDefinition"/>.
        /// Observable market data and existing known data are also needed to complete the calibration.
        /// </para>
        /// <para>
        /// A curve must only exist in one group.
        ///
        /// </para>
        /// </summary>
        /// <param name="allGroupsDefn">  the curve group definitions </param>
        /// <param name="knownData">  the starting data for the calibration </param>
        /// <param name="marketData">  the market data required to build a trade for the instrument </param>
        /// <param name="refData">  the reference data, used to resolve the trades </param>
        /// <returns> the rates provider resulting from the calibration </returns>
        public ImmutableRatesProvider calibrate(IList <RatesCurveGroupDefinition> allGroupsDefn, ImmutableRatesProvider knownData, MarketData marketData, ReferenceData refData)
        {
            // this method effectively takes one CurveGroupDefinition
            // the list is a split of the definition, not multiple independent definitions

            if (!knownData.ValuationDate.Equals(marketData.ValuationDate))
            {
                throw new System.ArgumentException(Messages.format("Valuation dates do not match: {} and {}", knownData.ValuationDate, marketData.ValuationDate));
            }
            // perform calibration one group at a time, building up the result by mutating these variables
            ImmutableRatesProvider             providerCombined           = knownData;
            ImmutableList <CurveParameterSize> orderPrev                  = ImmutableList.of();
            ImmutableMap <CurveName, JacobianCalibrationMatrix> jacobians = ImmutableMap.of();

            foreach (RatesCurveGroupDefinition groupDefn in allGroupsDefn)
            {
                if (groupDefn.Entries.Empty)
                {
                    continue;
                }
                RatesCurveGroupDefinition groupDefnBound = groupDefn.bindTimeSeries(knownData.ValuationDate, knownData.TimeSeries);
                // combine all data in the group into flat lists
                ImmutableList <ResolvedTrade>      trades            = groupDefnBound.resolvedTrades(marketData, refData);
                ImmutableList <double>             initialGuesses    = groupDefnBound.initialGuesses(marketData);
                ImmutableList <CurveParameterSize> orderGroup        = toOrder(groupDefnBound);
                ImmutableList <CurveParameterSize> orderPrevAndGroup = ImmutableList.builder <CurveParameterSize>().addAll(orderPrev).addAll(orderGroup).build();

                // calibrate
                RatesProviderGenerator providerGenerator     = ImmutableRatesProviderGenerator.of(providerCombined, groupDefnBound, refData);
                DoubleArray            calibratedGroupParams = calibrateGroup(providerGenerator, trades, initialGuesses, orderGroup);
                ImmutableRatesProvider calibratedProvider    = providerGenerator.generate(calibratedGroupParams);

                // use calibration to build Jacobian matrices
                if (groupDefnBound.ComputeJacobian)
                {
                    jacobians = updateJacobiansForGroup(calibratedProvider, trades, orderGroup, orderPrev, orderPrevAndGroup, jacobians);
                }
                ImmutableMap <CurveName, DoubleArray> sensitivityToMarketQuote = ImmutableMap.of();
                if (groupDefnBound.ComputePvSensitivityToMarketQuote)
                {
                    ImmutableRatesProvider providerWithJacobian = providerGenerator.generate(calibratedGroupParams, jacobians);
                    sensitivityToMarketQuote = sensitivityToMarketQuoteForGroup(providerWithJacobian, trades, orderGroup);
                }
                orderPrev = orderPrevAndGroup;

                // use Jacobians to build output curves
                providerCombined = providerGenerator.generate(calibratedGroupParams, jacobians, sensitivityToMarketQuote);
            }
            // return the calibrated provider
            return(providerCombined);
        }
Example #42
0
//--------------------------------------

        protected override void Initialize()
        {
            _marketDepth          = MarketData.GetMarketDepth(Symbol);
            _marketDepth.Updated += MarketDepthUpdated;

            BidVolume = CreateDataSeries();
            AskVolume = CreateDataSeries();

            zigzag = Indicators.GetIndicator <ZigZag>(Depth, Deviation, BackStep);

            foreach (var entry in _marketDepth.BidEntries)
            {
                PreviousBidList.Add(new Previouslist
                {
                    Preis   = entry.Price,
                    Volumen = entry.Volume
                });
            }

            foreach (var entry in _marketDepth.AskEntries)
            {
                PreviousAskList.Add(new Previouslist
                {
                    Preis   = entry.Price,
                    Volumen = entry.Volume
                });
            }

            LowFilterM  = LowFilter * 1000000;
            HighFilterM = HighFilter * 1000000;
            fname       = string.Format("{0}{1}{2}{3}", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "\\", FileName == "" ? Symbol.Code : FileName, ".csv");
            if (ReadFromFile && System.IO.File.Exists(fname) == true)
            {
                using (StreamReader Fstream = new StreamReader(fname))
                {
                    string line;
                    while ((line = Fstream.ReadLine()) != null)
                    {
                        try
                        {
                            string[] words = line.Split(Delimiters);
                            double   vol   = Convert.ToDouble(words[1]);
                            if (vol >= HighFilterM || vol < LowFilterM)
                            {
                                continue;
                            }
                            int bago = BarsAgo(Convert.ToDateTime(words[0]));
                            if (bago == -1)
                            {
                                continue;
                            }
                            int bidx = MarketSeries.Close.Count - 1 - bago;
                            if (double.IsNaN(AskVolume[bidx]))
                            {
                                AskVolume[bidx] = 0;
                            }
                            if (double.IsNaN(BidVolume[bidx]))
                            {
                                BidVolume[bidx] = 0;
                            }
                            switch (words[2])
                            {
                            case "A":
                                AskVolume[bidx] += (vol / 1000000);
                                break;

                            case "B":
                                BidVolume[bidx] -= (vol / 1000000);
                                break;
                            }
                        } catch
                        {
                            continue;
                        }
                    }
                }
            }
            if (WriteToFile)
            {
                if (System.IO.File.Exists(fname) == false)
                {
                    System.IO.File.WriteAllText(fname, "");
                }
                Timer.Start(WriteInterval);
            }
        }
 /// <summary>
 /// Create a new SellEventArgs with the specified quantity
 /// </summary>
 /// <param name="marketData">The market data</param>
 /// <param name="Shares">The number of Shares to purchase</param>
 public SellEventArgs(IPosition position, MarketData marketData)
     : base(TradeType.Sell, position, marketData)
 {
 }
 public bool AddMarketData(MarketData disownObject)
 {
     bool ret = otapiPINVOKE.MarketList_AddMarketData(swigCPtr, MarketData.getCPtr(disownObject));
     if (otapiPINVOKE.SWIGPendingException.Pending) throw otapiPINVOKE.SWIGPendingException.Retrieve();
     return ret;
 }
 internal TickerChangedEventArgs(CurrencyPair currencyPair, MarketData marketData)
 {
     CurrencyPair = currencyPair;
     MarketData   = marketData;
 }
Example #46
0
 protected override void Initialize()
 {
     GBPUSD          = MarketData.GetMarketDepth(Symbol);
     GBPUSD.Updated += OnGbpUsdUpdated;
 }
Example #47
0
        /// <summary>
        /// Parto dalle ultime candele personalizzate e le disegno ogni volta
        /// </summary>
        /// <param name="index"></param>
        private void _drawLevelFromCustomBar()
        {
            // --> Prelevo le candele daily
            Bars BarsCustom = MarketData.GetBars(CandleTimeFrame);

            int index = BarsCustom.Count - 1;

            // --> Potrei non avere un numero sufficiente di candele
            if (index < CandleShow || index < 1)
            {
                return;
            }

            // --> eseguo un ciclo aretroso per disegnare le ultime candele
            for (int i = 0; i < CandleShow; i++)
            {
                // --> Il numero di candele da visualizzare potrebbero essere troppe
                try
                {
                    // --> TimeSpan DiffTime = BarsCustom[index - i].OpenTime.Subtract(BarsCustom[(index - i) - 1].OpenTime); // <-- Strategia da valutare

                    DateTime thisCandle = BarsCustom[index - i].OpenTime;
                    DateTime nextCandle = (i == 0) ? thisCandle.AddMinutes(_getTimeFrameCandleInMinutes(CandleTimeFrame)) : BarsCustom[index - i + 1].OpenTime;

                    string rangeFlag  = thisCandle.ToString();
                    string RangeColor = (BarsCustom[index - i].Close > BarsCustom[index - i].Open) ? ColorHigh : ColorLow;

                    switch (MyCandleMode)
                    {
                    case CandleMode.HighLow:

                        if (Boxed)
                        {
                            ChartRectangle MyBox = Chart.DrawRectangle("HighLow" + rangeFlag, thisCandle, BarsCustom[index - i].High, nextCandle, BarsCustom[index - i].Low, Color.FromArgb(Opacity, Color.FromName(RangeColor)), TicknessBox, LineStyleBox);

                            MyBox.IsFilled = FillBox;
                        }
                        else
                        {
                            Chart.DrawTrendLine("High" + rangeFlag, thisCandle, BarsCustom[index - i].High, nextCandle, BarsCustom[index - i].High, Color.FromName(ColorHigh), TicknessBox, LineStyleBox);
                            Chart.DrawTrendLine("Low" + rangeFlag, thisCandle, BarsCustom[index - i].Low, nextCandle, BarsCustom[index - i].Low, Color.FromName(ColorLow), TicknessBox, LineStyleBox);
                        }

                        break;

                    case CandleMode.OpenClose:

                        if (Boxed)
                        {
                            ChartRectangle MyBox = Chart.DrawRectangle("OpenClose" + rangeFlag, thisCandle, BarsCustom[index - i].Open, nextCandle, BarsCustom[index - i].Close, Color.FromArgb(Opacity, Color.FromName(RangeColor)), TicknessBox, LineStyleBox);

                            MyBox.IsFilled = FillBox;
                        }
                        else
                        {
                            Chart.DrawTrendLine("Open" + rangeFlag, thisCandle, BarsCustom[index - i].Open, nextCandle, BarsCustom[index - i].Open, Color.FromName(ColorHigh), TicknessBox, LineStyleBox);
                            Chart.DrawTrendLine("Close" + rangeFlag, thisCandle, BarsCustom[index - i].Close, nextCandle, BarsCustom[index - i].Close, Color.FromName(ColorLow), TicknessBox, LineStyleBox);
                        }

                        break;
                    }
                } catch
                {
                }
            }
        }
 //-------------------------------------------------------------------------
 /// <summary>
 /// Obtains an instance based on a lookup and market data.
 /// <para>
 /// The lookup knows how to obtain the volatilities from the market data.
 /// This might involve accessing a surface or a cube.
 ///
 /// </para>
 /// </summary>
 /// <param name="lookup">  the lookup </param>
 /// <param name="marketData">  the market data </param>
 /// <returns> the rates market view </returns>
 public static DefaultIborCapFloorMarketData of(IborCapFloorMarketDataLookup lookup, MarketData marketData)
 {
     return(new DefaultIborCapFloorMarketData(lookup, marketData));
 }
Example #49
0
        public bool ProcessRules(StockInfo stockInfo, StockExchange stockExchange)//int ruleType, symbol, ruleXML
        {
            bool        result_TaLib               = false;
            bool        result_PriceBar            = false;
            bool        result_PrevioudDayPriceBar = false;
            bool        result_CurrentDayPriceBar  = false;
            bool        result_Indices             = false;
            bool        result_Sentiments          = false;
            bool        result_NASDAQindicator     = false;
            MarketQuote marketQoute = new MarketQuote();

            //create Stock object which is the feed for Codefeects rule engine
            Stock e_stock = new Stock();

            e_stock.Symbol          = stockInfo.stock_symbol;
            e_stock.StockID         = stockInfo.stock_ID;
            e_stock.StockExchangeID = stockExchange.stockExchange_ID;

            try
            {
                // fill with market data - open close high low

                marketQoute = APIReader.GetCurrentMarketData(stockInfo.stock_symbol, stockExchange);
            }
            catch (Exception)
            {
                Console.WriteLine("ERR in GetCurrentMarketData()");
            }

            result_CurrentDayPriceBar = MarketData.UpdateStockObjectWithMarketData(marketQoute, ref e_stock);

            //get History data
            List <Candle> candles = new List <Candle>();

            try
            {
                candles = APIReader.GetPriceHistory(stockInfo.stock_symbol, stockExchange);
            }
            catch (Exception)
            {
                Console.WriteLine("ERR in GetPriceHistory()");
            }


            //build a stock qoute object which will be used for all other calculations. this is holding data which needs for other analysis
            StockQuote stockQuote = new StockQuote();

            stockQuote.stock_candles = candles;

            //fill with previous day market data
            result_PrevioudDayPriceBar = MarketData.UpdateStockObjectWithPreviousDayData(stockQuote, ref e_stock);

            //fill with Talib values
            //   result_TaLib = TaLib.UpdateStockObjectWithTechnicalAnalysisData(stockQuote, ref e_stock);


            //get volatality factor)
            result_Indices = Indices.UpdateStockObjectWithIndicesData(stockQuote, ref e_stock);


            //Get sentinments)
            result_Sentiments = Sentiments.UpdateStockObjectWithSentimentData(ref e_stock);



            //get rule xml

            //if (ruleType == 1) //execute
            //{
            //    ///execute rule xml
            /// //// Get the rule XML


            //// Load Rule XML from the storage as a string
            List <CERule> rules = new List <CERule>();

            rules = ShareBook.App.Engine.Common.Data.DB.LoadRuleXml(1);
            foreach (CERule rule in rules)
            {
                Evaluator <Stock> evaluator = new Evaluator <Stock>(rule.RuleXml);

                try
                {
                    e_stock.RuleID = rule.RuleID;
                    // Evaluate the rule against the patient
                    bool success = evaluator.Evaluate(e_stock);
                }
                catch (DivideByZeroException)
                {
                    Console.WriteLine("ERR at rule evaluation-DivideByZeroException");
                    return(false);
                }
                catch (FormatException)
                {
                    Console.WriteLine("ERR at rule evaluation-FormatException");
                    return(false);
                }
            }
            return(true);
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @ImmutableConstructor private DefaultIborCapFloorMarketData(IborCapFloorMarketDataLookup lookup, com.opengamma.strata.data.MarketData marketData)
        private DefaultIborCapFloorMarketData(IborCapFloorMarketDataLookup lookup, MarketData marketData)
        {
            this.lookup     = ArgChecker.notNull(lookup, "lookup");
            this.marketData = ArgChecker.notNull(marketData, "marketData");
        }
        private void InitializeSeries(string symbolCode)
        {
            _symbol2 = MarketData.GetSymbol(symbolCode);

            _series2 = MarketData.GetSeries(_symbol2, TimeFrame);
        }
 //-------------------------------------------------------------------------
 public IborCapFloorMarketData withMarketData(MarketData marketData)
 {
     return(DefaultIborCapFloorMarketData.of(lookup, marketData));
 }
Example #53
0
    private IEnumerator DownloadMarket()
    {
        MarketData.dataMap.Clear();
        items.Clear();
        WWW d = new WWW(SystemConfig.GetCfgInfoUrl(SystemConfig.MARKET_URL_KEY));
        yield return d;
        var xml = XMLParser.LoadXML(d.text);
        var map = XMLParser.LoadIntMap(xml, SystemConfig.MARKET_URL_KEY);
        var type = typeof(MarketData);
        var props = type.GetProperties();
        foreach (var item in map)
        {
            var t = new MarketData();
            foreach (var prop in props)
            {
                if (prop.Name == "id")
                {
                    prop.SetValue(t, item.Key, null);
                }
                else
                {
                    if (item.Value.ContainsKey(prop.Name))
                    {
                        var value = Utils.GetValue(item.Value[prop.Name], prop.PropertyType);
                        prop.SetValue(t, value, null);
                    }
                }
            }
            if (!MarketData.dataMap.ContainsKey(item.Key))
            {
                MarketData.dataMap.Add(item.Key, t);
            }
            version = t.marketVersion;
            items.Add(new MarketItem(t));
        }
        foreach (var i in items)
        {
            if (i.resData.mode == 2)
            {//限购
                GetLimitNum(i.resData.marketVersion, i.resData.id);
            }
        }

        ShowMarketUIByTab();   
    }
Example #54
0
        TriState _ModifyPending(double magicIndex, string symbolCode, int slAction, double slValue, int tpAction, double tpValue, int priceAction, double priceValue, int expirationAction, DateTime?expiration)
        {
            Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);
            var    po     = PendingOrders.__Find("FxProQuant_" + magicIndex.ToString("F0"), symbol);

            if (po == null)
            {
                return(new TriState());
            }
            double targetPrice;
            double?sl, tp;

            if (slValue == 0)
            {
                sl = null;
            }
            else
            {
                switch (slAction)
                {
                case 0:
                    sl = po.StopLoss;
                    break;

                case 1:
                    if (po.TradeType == TradeType.Buy)
                    {
                        sl = po.TargetPrice - slValue * symbol.TickSize;
                    }
                    else
                    {
                        sl = po.TargetPrice + slValue * symbol.TickSize;
                    }
                    break;

                case 2:
                    sl = slValue;
                    break;

                default:
                    sl = po.StopLoss;
                    break;
                }
            }
            if (tpValue == 0)
            {
                tp = null;
            }
            else
            {
                switch (tpAction)
                {
                case 0:
                    tp = po.TakeProfit;
                    break;

                case 1:
                    if (po.TradeType == TradeType.Buy)
                    {
                        tp = po.TargetPrice + tpValue * symbol.TickSize;
                    }
                    else
                    {
                        tp = po.TargetPrice - tpValue * symbol.TickSize;
                    }
                    break;

                case 2:
                    tp = tpValue;
                    break;

                default:
                    tp = po.TakeProfit;
                    break;
                }
            }
            switch (priceAction)
            {
            case 0:
                targetPrice = po.TargetPrice;
                break;

            case 1:
                targetPrice = priceValue;
                break;

            case 2:
                targetPrice = po.TargetPrice + priceValue * symbol.TickSize;
                break;

            case 3:
                targetPrice = po.TargetPrice - priceValue * symbol.TickSize;
                break;

            case 4:
                targetPrice = symbol.Bid - priceValue * symbol.TickSize;
                break;

            case 5:
                targetPrice = symbol.Bid + priceValue * symbol.TickSize;
                break;

            case 6:
                targetPrice = symbol.Ask - priceValue * symbol.TickSize;
                break;

            case 7:
                targetPrice = symbol.Ask + priceValue * symbol.TickSize;
                break;

            default:
                targetPrice = po.TargetPrice;
                break;
            }
            if (expiration.HasValue && (expiration.Value.Ticks == 0 || expiration.Value == DateTime.Parse("1970.01.01 00:00:00")))
            {
                expiration = null;
            }
            if (expirationAction == 0)
            {
                expiration = po.ExpirationTime;
            }
            if (!ModifyPendingOrder(po, targetPrice, sl, tp, expiration).IsSuccessful)
            {
                Thread.Sleep(400);
                return(false);
            }
            return(true);
        }
        static CalibrationDiscountFactorUsd2FomcDatesOisIrsTest()
        {
            DSC_NAMES[DSCON_CURVE_NAME] = USD;
            ISet <Index> usdFedFundSet = new HashSet <Index>();

            usdFedFundSet.Add(USD_FED_FUND);
            IDX_NAMES[DSCON_CURVE_NAME] = usdFedFundSet;
            ISet <Index> usdLibor3Set = new HashSet <Index>();

            usdLibor3Set.Add(USD_LIBOR_3M);
            IDX_NAMES[FWD3_CURVE_NAME] = usdLibor3Set;
            double fixingValue = 0.002345;
            LocalDateDoubleTimeSeries tsBdUsdLibor3M = LocalDateDoubleTimeSeries.builder().put(VAL_DATE_BD, fixingValue).build();

            TS_BD_LIBOR3M = ImmutableMarketData.builder(VAL_DATE_BD).addTimeSeries(IndexQuoteId.of(USD_LIBOR_3M), tsBdUsdLibor3M).build();
            for (int i = 0; i < DSC_NB_DEPO_NODES; i++)
            {
                BusinessDayAdjustment bda        = BusinessDayAdjustment.of(FOLLOWING, USNY);
                TermDepositConvention convention = ImmutableTermDepositConvention.of("USD-Dep", USD, bda, ACT_360, DaysAdjustment.ofBusinessDays(DSC_DEPO_OFFSET[i], USNY));
                LocalDate             nodeDate   = FOMC_NODES[i];
                if (nodeDate != null)
                {
                    DSC_NODES[i] = TermDepositCurveNode.builder().template(TermDepositTemplate.of(Period.ofDays(1), convention)).rateId(QuoteId.of(StandardId.of(SCHEME, DSC_ID_VALUE[i]))).date(CurveNodeDate.of(nodeDate)).build();
                }
                else
                {
                    DSC_NODES[i] = TermDepositCurveNode.of(TermDepositTemplate.of(Period.ofDays(1), convention), QuoteId.of(StandardId.of(SCHEME, DSC_ID_VALUE[i])));
                }
            }
            for (int i = 0; i < DSC_NB_OIS_NODES; i++)
            {
                LocalDate nodeDate = FOMC_NODES[DSC_NB_DEPO_NODES + i];
                if (nodeDate != null)
                {
                    DSC_NODES[DSC_NB_DEPO_NODES + i] = FixedOvernightSwapCurveNode.builder().template(FixedOvernightSwapTemplate.of(Period.ZERO, Tenor.of(DSC_OIS_TENORS[i]), USD_FIXED_1Y_FED_FUND_OIS)).rateId(QuoteId.of(StandardId.of(SCHEME, DSC_ID_VALUE[DSC_NB_DEPO_NODES + i]))).date(CurveNodeDate.of(nodeDate)).build();
                }
                else
                {
                    DSC_NODES[DSC_NB_DEPO_NODES + i] = FixedOvernightSwapCurveNode.of(FixedOvernightSwapTemplate.of(Period.ZERO, Tenor.of(DSC_OIS_TENORS[i]), USD_FIXED_1Y_FED_FUND_OIS), QuoteId.of(StandardId.of(SCHEME, DSC_ID_VALUE[DSC_NB_DEPO_NODES + i])));
                }
            }
            FWD3_NODES[0] = IborFixingDepositCurveNode.of(IborFixingDepositTemplate.of(USD_LIBOR_3M), QuoteId.of(StandardId.of(SCHEME, FWD3_ID_VALUE[0])));
            for (int i = 0; i < FWD3_NB_FRA_NODES; i++)
            {
                FWD3_NODES[i + 1] = FraCurveNode.of(FraTemplate.of(FWD3_FRA_TENORS[i], USD_LIBOR_3M), QuoteId.of(StandardId.of(SCHEME, FWD3_ID_VALUE[i + 1])));
            }
            for (int i = 0; i < FWD3_NB_IRS_NODES; i++)
            {
                FWD3_NODES[i + 1 + FWD3_NB_FRA_NODES] = FixedIborSwapCurveNode.of(FixedIborSwapTemplate.of(Period.ZERO, Tenor.of(FWD3_IRS_TENORS[i]), USD_FIXED_6M_LIBOR_3M), QuoteId.of(StandardId.of(SCHEME, FWD3_ID_VALUE[i + 1 + FWD3_NB_FRA_NODES])));
            }
            ImmutableMarketDataBuilder builder = ImmutableMarketData.builder(VAL_DATE_BD);

            for (int i = 0; i < FWD3_NB_NODES; i++)
            {
                builder.addValue(QuoteId.of(StandardId.of(SCHEME, FWD3_ID_VALUE[i])), FWD3_MARKET_QUOTES[i]);
            }
            for (int i = 0; i < DSC_NB_NODES; i++)
            {
                builder.addValue(QuoteId.of(StandardId.of(SCHEME, DSC_ID_VALUE[i])), DSC_MARKET_QUOTES[i]);
            }
            ALL_QUOTES_BD = builder.build();
            IList <CurveNode[]> groupDsc = new List <CurveNode[]>();

            groupDsc.Add(DSC_NODES);
            CURVES_NODES.Add(groupDsc);
            IList <CurveNode[]> groupFwd3 = new List <CurveNode[]>();

            groupFwd3.Add(FWD3_NODES);
            CURVES_NODES.Add(groupFwd3);
            IList <CurveMetadata> groupDsc = new List <CurveMetadata>();

            groupDsc.Add(DefaultCurveMetadata.builder().curveName(DSCON_CURVE_NAME).xValueType(ValueType.YEAR_FRACTION).yValueType(ValueType.ZERO_RATE).dayCount(CURVE_DC).build());
            CURVES_METADATA.Add(groupDsc);
            IList <CurveMetadata> groupFwd3 = new List <CurveMetadata>();

            groupFwd3.Add(DefaultCurveMetadata.builder().curveName(FWD3_CURVE_NAME).xValueType(ValueType.YEAR_FRACTION).yValueType(ValueType.ZERO_RATE).dayCount(CURVE_DC).build());
            CURVES_METADATA.Add(groupFwd3);
        }
Example #56
0
        private void SimpleLogic()
        {
            if (initial_start)
            {
                TRAILING();
                {
                    //SMA Trend
                    var MA1 = SMATrend.Result.Last(1);

                    //Pivot Points Levels
                    var PivotPoints = MarketData.GetSeries(PivotPointTimeFrame);

                    var closepip = PivotPoints.Close.Last(1);
                    var Pricey   = (Symbol.Ask + Symbol.Bid) / 2;

                    var highest = MarketSeries.High.Last(1);
                    var lowest  = MarketSeries.Low.Last(1);

                    //Pivot Points: Levels
                    var PP = (highest + lowest + closepip) / 3;
                    var R4 = 3 * PP + (highest - 3 * lowest);
                    var R3 = 2 * PP + (highest - 2 * lowest);
                    var R2 = PP + (highest - lowest);
                    var R1 = 2 * PP - lowest;
                    var S1 = 2 * PP - highest;
                    var S2 = PP - (highest - lowest);
                    var S3 = 2 * PP - (2 * highest - lowest);
                    var S4 = 3 * PP - (3 * highest - lowest);


                    //Pivot Point Range
                    var highestR = MarketSeries.High.Last(1);
                    for (int i = 2; i <= Periods; i++)
                    {
                        if (MarketSeries.High.Last(i) > highestR)
                        {
                            highestR = MarketSeries.High.Last(i);
                        }
                    }

                    var lowestR = MarketSeries.Low.Last(1);
                    for (int i = 2; i <= Periods; i++)
                    {
                        if (MarketSeries.Low.Last(i) < lowestR)
                        {
                            lowestR = MarketSeries.Low.Last(i);
                        }
                    }

                    //Pivot Points: Range
                    var R4R = 3 * PP + (highestR - 3 * lowestR);
                    var R3R = 2 * PP + (highestR - 2 * lowestR);
                    var R2R = PP + (highestR - lowestR);
                    var R1R = 2 * PP - lowestR;
                    var S1R = 2 * PP - highestR;
                    var S2R = PP - (highestR - lowestR);
                    var S3R = 2 * PP - (2 * highestR - lowestR);
                    var S4R = 3 * PP - (3 * highestR - lowestR);


                    //Entry Signal previous bar larger than the one before
                    if ((FirstTrend ? (Trend ? closepip >= MA1 : true) && (PivotPointsYN ? (PivotPointsLevels ? Pricey <= (activeDirectionCount(TradeType.Buy) < PositionsLevels ? S1 : (activeDirectionCount(TradeType.Buy) >= PositionsLevels && activeDirectionCount(TradeType.Buy) < PositionsLevels * 2 ? S2 : (activeDirectionCount(TradeType.Buy) >= PositionsLevels * 2 && activeDirectionCount(TradeType.Buy) < PositionsLevels * 3 ? S3 : S4))) : (Pricey <= (PivotSupport == 1 ? S1R : (PivotSupport == 2 ? S2R : (PivotSupport == 3 ? S3R : S4R))))) : true) : true) && Buy >= 1 && activeDirectionCount(TradeType.Buy) == 0 && MarketSeries.Close.Last(1) > MarketSeries.Close.Last(2))
                    {
                        orderStatus = OrderSend(TradeType.Buy, Volumizer(FirstVolume));
                        if (orderStatus > 0)
                        {
                            buyOpenTime = MarketSeries.OpenTime.Last(0);
                        }
                        else
                        {
                            Print("First BUY openning error at: ", Symbol.Ask, "Error Type: ", LastResult.Error);
                        }
                    }
                    //Entry signal  previous bar smaller than the one before
                    if ((FirstTrend ? (Trend ? closepip <= MA1 : true) && (PivotPointsYN ? (PivotPointsLevels ? Pricey >= (activeDirectionCount(TradeType.Sell) < PositionsLevels ? R1 : (activeDirectionCount(TradeType.Sell) >= PositionsLevels && activeDirectionCount(TradeType.Sell) < PositionsLevels * 2 ? R2 : (activeDirectionCount(TradeType.Sell) >= PositionsLevels * 2 && activeDirectionCount(TradeType.Sell) < PositionsLevels * 3 ? R3 : R4))) : (Pricey >= (PivotResistance == 1 ? R1R : (PivotResistance == 2 ? R2R : (PivotResistance == 3 ? R3R : R4R))))) : true) : true) && Sell >= 1 && activeDirectionCount(TradeType.Sell) == 0 && MarketSeries.Close.Last(2) > MarketSeries.Close.Last(1))
                    {
                        orderStatus = OrderSend(TradeType.Sell, Volumizer(FirstVolume));
                        if (orderStatus > 0)
                        {
                            sellOpenTime = MarketSeries.OpenTime.Last(0);
                        }
                        else
                        {
                            Print("First SELL openning error at: ", Symbol.Bid, "Error Type: ", LastResult.Error);
                        }
                    }
                }
                Gridernize();
            }
        }
Example #57
0
        TriState _SendPending(double magicIndex, bool noOrders, string symbolCode, PendingOrderType poType, TradeType tradeType, double lots, int priceAction, double priceValue, double?stopLoss, double?takeProfit,
                              DateTime?expiration, string comment)
        {
            Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);

            if (noOrders && PendingOrders.__Find("FxProQuant_" + magicIndex.ToString("F0"), symbol) != null)
            {
                return(new TriState());
            }
            if (stopLoss < 1)
            {
                stopLoss = null;
            }
            if (takeProfit < 1)
            {
                takeProfit = null;
            }
            if (symbol.Digits == 5 || symbol.Digits == 3)
            {
                if (stopLoss != null)
                {
                    stopLoss /= 10;
                }
                if (takeProfit != null)
                {
                    takeProfit /= 10;
                }
            }
            int    volume = (int)(lots * 100000);
            double targetPrice;

            switch (priceAction)
            {
            case 0:
                targetPrice = priceValue;
                break;

            case 1:
                targetPrice = symbol.Bid - priceValue * symbol.TickSize;
                break;

            case 2:
                targetPrice = symbol.Bid + priceValue * symbol.TickSize;
                break;

            case 3:
                targetPrice = symbol.Ask - priceValue * symbol.TickSize;
                break;

            case 4:
                targetPrice = symbol.Ask + priceValue * symbol.TickSize;
                break;

            default:
                targetPrice = priceValue;
                break;
            }
            if (expiration.HasValue && (expiration.Value.Ticks == 0 || expiration.Value == DateTime.Parse("1970.01.01 00:00:00")))
            {
                expiration = null;
            }
            if (poType == PendingOrderType.Limit)
            {
                if (!PlaceLimitOrder(tradeType, symbol, volume, targetPrice, "FxProQuant_" + magicIndex.ToString("F0"), stopLoss, takeProfit, expiration, comment).IsSuccessful)
                {
                    Thread.Sleep(400);
                    return(false);
                }
                return(true);
            }
            else if (poType == PendingOrderType.Stop)
            {
                if (!PlaceStopOrder(tradeType, symbol, volume, targetPrice, "FxProQuant_" + magicIndex.ToString("F0"), stopLoss, takeProfit, expiration, comment).IsSuccessful)
                {
                    Thread.Sleep(400);
                    return(false);
                }
                return(true);
            }
            return(new TriState());
        }
Example #58
0
        //Create the Grid sistem based on the PipStep
        private void Gridernize()
        {
            TRAILING();
            {
                //SMA Trend
                var MA1 = SMATrend.Result.Last(1);

                //Pivot Points Levels
                var PivotPoints = MarketData.GetSeries(PivotPointTimeFrame);

                var closepip = PivotPoints.Close.Last(1);
                var Pricey   = (Symbol.Ask + Symbol.Bid) / 2;

                var highest = MarketSeries.High.Last(1);
                var lowest  = MarketSeries.Low.Last(1);

                //Pivot Points: Levels
                var PP = (highest + lowest + closepip) / 3;
                var R4 = 3 * PP + (highest - 3 * lowest);
                var R3 = 2 * PP + (highest - 2 * lowest);
                var R2 = PP + (highest - lowest);
                var R1 = 2 * PP - lowest;
                var S1 = 2 * PP - highest;
                var S2 = PP - (highest - lowest);
                var S3 = 2 * PP - (2 * highest - lowest);
                var S4 = 3 * PP - (3 * highest - lowest);


                //Pivot Point Range
                var highestR = MarketSeries.High.Last(1);
                for (int i = 2; i <= Periods; i++)
                {
                    if (MarketSeries.High.Last(i) > highestR)
                    {
                        highestR = MarketSeries.High.Last(i);
                    }
                }

                var lowestR = MarketSeries.Low.Last(1);
                for (int i = 2; i <= Periods; i++)
                {
                    if (MarketSeries.Low.Last(i) < lowestR)
                    {
                        lowestR = MarketSeries.Low.Last(i);
                    }
                }

                //Pivot Points: Range
                var R4R = 3 * PP + (highestR - 3 * lowestR);
                var R3R = 2 * PP + (highestR - 2 * lowestR);
                var R2R = PP + (highestR - lowestR);
                var R1R = 2 * PP - lowestR;
                var S1R = 2 * PP - highestR;
                var S2R = PP - (highestR - lowestR);
                var S3R = 2 * PP - (2 * highestR - lowestR);
                var S4R = 3 * PP - (3 * highestR - lowestR);

                var PipSteps = CalculatePips();

                if ((Trend ? closepip >= MA1 : true) && (PivotPointsYN ? (PivotPointsLevels ? Pricey <= (activeDirectionCount(TradeType.Buy) < PositionsLevels ? S1 : (activeDirectionCount(TradeType.Buy) >= PositionsLevels && activeDirectionCount(TradeType.Buy) < PositionsLevels * 2 ? S2 : (activeDirectionCount(TradeType.Buy) >= PositionsLevels * 2 && activeDirectionCount(TradeType.Buy) < PositionsLevels * 3 ? S3 : S4))) : (Pricey <= (PivotSupport == 1 ? S1R : (PivotSupport == 2 ? S2R : (PivotSupport == 3 ? S3R : S4R))))) : true) && activeDirectionCount(TradeType.Buy) > 0 && activeDirectionCount(TradeType.Buy) < Buy)
                {
                    if (Math.Round(Symbol.Ask, Symbol.Digits) < Math.Round(GetHighestBuyEntry(TradeType.Buy) - (PipStep > 0 ? PipStep : PipSteps) * Symbol.PipSize, Symbol.Digits) && buyOpenTime != MarketSeries.OpenTime.Last(0))
                    {
                        long b_lotS = NextLotSize(TradeType.Buy);
                        orderStatus = OrderSend(TradeType.Buy, Volumizer(b_lotS));
                        if (orderStatus > 0)
                        {
                            buyOpenTime = MarketSeries.OpenTime.Last(0);
                        }
                        else
                        {
                            Print("Next BUY openning error at: ", Symbol.Ask, "Error Type: ", LastResult.Error);
                        }
                    }
                }

                if ((Trend ? closepip <= MA1 : true) && (PivotPointsYN ? (PivotPointsLevels ? Pricey >= (activeDirectionCount(TradeType.Sell) < PositionsLevels ? R1 : (activeDirectionCount(TradeType.Sell) >= PositionsLevels && activeDirectionCount(TradeType.Sell) < PositionsLevels * 2 ? R2 : (activeDirectionCount(TradeType.Sell) >= PositionsLevels * 2 && activeDirectionCount(TradeType.Sell) < PositionsLevels * 3 ? R3 : R4))) : (Pricey >= (PivotResistance == 1 ? R1R : (PivotResistance == 2 ? R2R : (PivotResistance == 3 ? R3R : R4R))))) : true) && activeDirectionCount(TradeType.Sell) > 0 && activeDirectionCount(TradeType.Sell) < Sell)
                {
                    if (Math.Round(Symbol.Bid, Symbol.Digits) > Math.Round(GetLowestSellEntry(TradeType.Sell) + (PipStep > 0 ? PipStep : PipSteps) * Symbol.PipSize, Symbol.Digits) && sellOpenTime != MarketSeries.OpenTime.Last(0))
                    {
                        long s_lotS = NextLotSize(TradeType.Sell);
                        orderStatus = OrderSend(TradeType.Sell, Volumizer(s_lotS));
                        if (orderStatus > 0)
                        {
                            sellOpenTime = MarketSeries.OpenTime.Last(0);
                        }
                        else
                        {
                            Print("Next SELL openning error at: ", Symbol.Bid, "Error Type: ", LastResult.Error);
                        }
                    }
                }
            }
        }
Example #59
0
        protected bool GetData(databases.baseDS.exchangeDetailRow exchangeDetailRow, ref MarketData hnIdx, ref MarketData hnIdx30)
        {
            clientSSI.AjaxWebServiceSoapClient client = null;
            try
            {
                client = new clientSSI.AjaxWebServiceSoapClient();
                client.Endpoint.Address = new System.ServiceModel.EndpointAddress(exchangeDetailRow.address);
                System.ServiceModel.BasicHttpBinding binding = (client.Endpoint.Binding as System.ServiceModel.BasicHttpBinding);

                binding.OpenTimeout = TimeSpan.FromSeconds(Consts.constWebServiceTimeOutInSecs);
                binding.CloseTimeout = binding.OpenTimeout;
                binding.SendTimeout = binding.OpenTimeout;

                binding.MaxReceivedMessageSize = Consts.constWebServiceMaxReceivedMessageSize;
                binding.MaxBufferSize = Consts.constWebServiceMaxReceivedMessageSize;

                binding.ReaderQuotas.MaxStringContentLength = Consts.constWebServiceMaxStringContentLength;
                binding.ReaderQuotas.MaxBytesPerRead = Consts.constWebServiceMaxBytesPerRead;

                CultureInfo dataCulture = application.AppLibs.GetCulture(exchangeDetailRow.culture);
                String s = client.GetMarketAllIndex(0);//.GetDataHaSTC2_Index();
                List<string> tradeList = new List<string>(s.Split('#'));
                for (int i = 0; i < tradeList.Count; i++)
                {
                    List<string> tradeData = new List<string>(tradeList[i].Split('|'));
                    if (tradeData[5].Trim() == "")
                    {
                        continue;
                    }
                    hnIdx.Value = decimal.Parse(tradeData[5], dataCulture);
                    hnIdx.TotalQty = decimal.Parse(tradeData[3], dataCulture);
                    hnIdx.TotalAmt = decimal.Parse(tradeData[4], dataCulture);

                    hnIdx30.Value = decimal.Parse(tradeData[10], dataCulture);
                    hnIdx30.TotalQty = decimal.Parse(tradeData[11], dataCulture);
                    hnIdx30.TotalAmt = decimal.Parse(tradeData[12], dataCulture);
                    return true;
                }
            }
            catch (WebException e)
            {
                return false;
            }
            finally
            {
                if (client != null && client.State == System.ServiceModel.CommunicationState.Opened)
                    client.Close();
            }

            return true;
        }
Example #60
0
        //Forces refresh of all admin offered grids and syncs them to the blocks in the server
        public void UpdatePublicOffers()
        {
            //Update all public offer market items!


            //Need to remove existing ones
            for (int i = 0; i < GridList.Count; i++)
            {
                if (GridList[i].Steamid != 0)
                {
                    continue;
                }

                Hangar.Debug("Removing public offer: " + GridList[i].Name);
                GridList.RemoveAt(i);
            }

            string PublicOfferPath = ServerOffersDir;

            //Clear list
            PublicOfferseGridList.Clear();

            foreach (PublicOffers offer in Config.PublicOffers)
            {
                if (offer.Forsale)
                {
                    string GridFilePath = System.IO.Path.Combine(PublicOfferPath, offer.Name + ".sbc");


                    MyObjectBuilderSerializer.DeserializeXML(GridFilePath, out MyObjectBuilder_Definitions myObjectBuilder_Definitions);
                    MyObjectBuilder_ShipBlueprintDefinition[] shipBlueprint = null;
                    try
                    {
                        shipBlueprint = myObjectBuilder_Definitions.ShipBlueprints;
                    }
                    catch
                    {
                        Hangar.Debug("Error on BP: " + offer.Name + "! Most likely you put in the SBC5 file! Dont do that!");
                        continue;
                    }
                    MyObjectBuilder_CubeGrid grid = shipBlueprint[0].CubeGrids[0];
                    byte[] Definition             = MyAPIGateway.Utilities.SerializeToBinary(grid);

                    //HangarChecks.GetPublicOfferBPDetails(shipBlueprint, out GridStamp stamp);


                    //Straight up add new ones
                    MarketList NewList = new MarketList();
                    NewList.Steamid        = 0;
                    NewList.Name           = offer.Name;
                    NewList.Seller         = offer.Seller;
                    NewList.SellerFaction  = offer.SellerFaction;
                    NewList.Price          = offer.Price;
                    NewList.Description    = offer.Description;
                    NewList.GridDefinition = Definition;
                    //NewList.GridBuiltPercent = stamp.GridBuiltPercent;
                    //NewList.NumberofBlocks = stamp.NumberofBlocks;
                    //NewList.SmallGrids = stamp.SmallGrids;
                    //NewList.LargeGrids = stamp.LargeGrids;
                    // NewList.BlockTypeCount = stamp.BlockTypeCount;

                    //Need to setTotalBuys
                    PublicOfferseGridList.Add(NewList);

                    Hangar.Debug("Adding new public offer: " + offer.Name);
                }
            }

            //Update Everything!
            Comms.SendListToModOnInitilize();

            MarketData Data = new MarketData();

            Data.List = PublicOfferseGridList;

            FileSaver.Save(ServerMarketFileDir, Data);
        }