Exemple #1
0
        protected static ForexData Convert2ForexData(List <string> row)
        {
            decimal last = 0, high = 0, low = 0, changed = 0;

            if (!common.system.StrToDecimal(row[1].Trim(), myCulture, out last))
            {
                return(null);
            }
            string[] parts = row[2].Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            if (parts.Length < 2)
            {
                return(null);
            }
            if (!common.system.StrToDecimal(parts[0].Trim(), myCulture, out high))
            {
                return(null);
            }
            if (!common.system.StrToDecimal(parts[1].Trim(), myCulture, out low))
            {
                return(null);
            }
            if (!common.system.StrToDecimal(row[3].Trim(), myCulture, out changed))
            {
                return(null);
            }
            ForexData data = new ForexData();

            data.code    = row[0].Replace("/", "").Replace(" ", "");
            data.last    = last;
            data.high    = high;
            data.low     = low;
            data.changed = changed;
            return(data);
        }
Exemple #2
0
        public override databases.baseDS.priceDataDataTable GetImportFromWeb(DateTime updateTime, databases.baseDS.exchangeDetailRow exchangeDetailRow)
        {
            // Different culture has differebr strt of week, ie in VN culture : start of week is Monday (not Sunday)
            if (myCulture == null)
            {
                myCulture = application.AppLibs.GetCulture(exchangeDetailRow.culture);
            }

            databases.importDS.importPriceDataTable importPriceTbl = new databases.importDS.importPriceDataTable();
            ForexData goldData = ImportKitco(exchangeDetailRow.address);

            if (null == goldData)
            {
                return(null);
            }

            AddImportRow(updateTime, goldData, false, importPriceTbl);

            Imports.Libs.AddNewCode(exchangeDetailRow.marketCode, importPriceTbl, null);
            databases.DbAccess.UpdateData(importPriceTbl);

            databases.baseDS.priceDataDataTable priceTbl = new databases.baseDS.priceDataDataTable();
            Imports.Libs.AddImportPrice(importPriceTbl, priceTbl);
            databases.DbAccess.UpdateData(priceTbl);

            return(priceTbl);
        }
        public void SaveExtrapolateBuyData(ForexData fx)
        {
            ExpBuyInterval expData;
            string         refId = string.Empty;

            if (ConfigurationManager.AppSettings[Constants.Environment.ENVIRONMENT].ToString() == Constants.Environment.PROD)
            {
                FilterDefinition <ActiveTicker> filter = null;
                filter = Builders <ActiveTicker> .Filter.Where(sp => sp.Symbol == fx.Symbol && sp.AccountId == AccountID);

                ActiveTicker aTic = dbManager.GetEntity(filter);

                if (aTic != null)
                {
                    refId = aTic.Id;

                    FilterDefinition <ExpBuyInterval> filterExp = null;
                    filterExp = Builders <ExpBuyInterval> .Filter.Where(sp => sp.ReferanceId == refId && sp.TradeId == fx.TradeId);

                    if (dbManager.GetEntity(filterExp) == null)
                    {
                        expData = new ExpBuyInterval(refId, fx.TradeId, fx.Symbol, fx.PriceBuy, fx.Count, fx.PurchaseTime, fx.AccountId);
                        dbManager.InsertEntity <ExpBuyInterval>(expData);
                    }
                }
                else
                {
                    Console.WriteLine("Active ticker missing, error in logic");
                }
            }
        }
Exemple #4
0
        private static ForexData[] ImportForex(string url)
        {
            System.Net.WebRequest webReq = System.Net.WebRequest.Create(url);
            System.Net.WebResponse webRes = webReq.GetResponse();
            System.IO.Stream mystream = webRes.GetResponseStream();
            if (mystream == null) return null;

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

            int iColumn = 0;
            var myNode = myHtmlDoc.DocumentNode.SelectNodes("//table[@id='fund_list_table']/tr/td[1]");

            List<string> anchorTags = new List<string>();
            if (myNode == null) return null;

            ForexData[] result = new ForexData[0];
            foreach (HtmlNode link in myNode)
            {
                ++iColumn;
                string att = link.InnerText;
                HtmlNode thuxem = link.ParentNode;
                String attt = thuxem.InnerHtml;
                if (att == "Pair")
                {
                    HtmlNode nodeOfDataRow = link.ParentNode;   //Lấy node tên column
                    nodeOfDataRow = nodeOfDataRow.NextSibling;  // Lấy hàng dữ liệu đầu tiên
                    string asdf = nodeOfDataRow.InnerHtml;

                    while (nodeOfDataRow != null)
                    {
                        HtmlNode nodeOfRow = nodeOfDataRow.FirstChild;  //Lấy ô dữ liệu đầu tiên
                        List<String> row = new List<string>();
                        while (nodeOfRow != null)   // Lấy các ô dữ liệu tiếp theo
                        {
                            //Kiem tra xem chuoi co hop le
                            if (!nodeOfRow.InnerText.Contains("<!--") && nodeOfRow.InnerText.Length > 0)
                                row.Add(nodeOfRow.InnerText);
                            nodeOfRow = nodeOfRow.NextSibling;
                        }
                        if (row.Count >= 4)
                        {
                            ForexData data = Convert2ForexData(row);
                            if (data != null)
                            {
                                Array.Resize(ref result, result.Length + 1);
                                result[result.Length - 1] = data;
                            }
                        }
                        nodeOfDataRow = nodeOfDataRow.NextSibling;  // Lay Du Lieu Dong Tiep theo
                    }
                }
            }
            return result;
        }
Exemple #5
0
        public void ReceiveData(ForexData data)
        {
            List <KeyValuePair <DateTime, double> > list = new List <KeyValuePair <DateTime, double> >();

            foreach (var item in data.Data)
            {
                list.Add(new KeyValuePair <DateTime, double>(new DateTime(item.Key, DateTimeKind.Utc), item.Value));
            }

            OnReceiveDataEvent(this, new ReceiveDataArgs(data.Name, list));
        }
Exemple #6
0
        /// <summary>
        /// Gets data from database
        /// </summary>
        /// <param name="count"></param>
        /// <param name="tradingPair"></param>
        /// <returns></returns>
        public List <KeyValuePair <DateTime, double> > GetData(int count, string tradingPair)
        {
            ForexData forexData = _tradingServiceClient.GetData(count, tradingPair);
            List <KeyValuePair <DateTime, double> > list = new List <KeyValuePair <DateTime, double> >();

            foreach (var item in forexData.Data)
            {
                list.Add(new KeyValuePair <DateTime, double>(new DateTime(item.Key, DateTimeKind.Utc), item.Value));
            }
            return(list);
        }
Exemple #7
0
        private static data.importDS.importPriceDataTable GetPrice(DateTime updateTime, string url, string marketCode)
        {
            data.importDS.importPriceDataTable importPriceTbl = new data.importDS.importPriceDataTable();
            ForexData[] frData   = ImportForex(url);
            ForexData   goldData = frData[3]; //Gold at price 4

            if (lastForexData != null)
            {
                if (lastForexData.last == goldData.last &&
                    lastForexData.high == goldData.high &&
                    lastForexData.low == goldData.low)
                {
                    return(importPriceTbl);
                }
            }
            else
            {
                lastForexData = new ForexData();
            }
            lastForexData.last = goldData.last;
            lastForexData.high = goldData.high;
            lastForexData.low  = goldData.low;

            data.importDS.importPriceRow importRow;
            importRow = importPriceTbl.NewimportPriceRow();
            application.DbAccess.InitData(importRow);
            importRow.onDate        = updateTime;
            importRow.stockExchange = marketCode;
            importRow.stockCode     = goldData.code;
            importRow.closePrice    = goldData.last;
            importRow.highPrice     = goldData.high;
            importRow.lowPrice      = goldData.low;

            if (goldOpenPriceDate != updateTime.Date || goldOpenPrice == decimal.MinValue)
            {
                data.baseDS.priceDataRow row = application.DbAccess.GetLastPriceData(importRow.stockCode);
                if (row != null)
                {
                    goldOpenPrice = row.closePrice;
                }
                else
                {
                    goldOpenPrice = importRow.closePrice;
                }
                goldOpenPriceDate = updateTime.Date;
            }
            importRow.openPrice = goldOpenPrice;
            importPriceTbl.AddimportPriceRow(importRow);
            return(importPriceTbl);
        }
Exemple #8
0
        private ForexData GetFxStockFromTradeId(List <Position> posList, int id)
        {
            ForexData fxSt = null;

            foreach (ForexPosition fxP in posList)
            {
                fxSt = (ForexData)fxP.TradeList.Find(obj => obj.TradeId == id);
                if (fxSt != null)
                {
                    return(fxSt);
                }
            }
            return(fxSt);
        }
        public void SaveNewTrades()
        {
            ForexData fx           = null;
            JArray    trdOpenArray = JArray.Parse(NewTrades);

            foreach (JObject trdOpnItem in trdOpenArray)
            {
                fx              = new ForexData();
                fx.Symbol       = trdOpnItem["instrument"].Value <string>();
                fx.AccountId    = AccountID;
                fx.AccountType  = AccountType;
                fx.Count        = trdOpnItem["currentUnits"].Value <decimal>();
                fx.PriceBuy     = trdOpnItem["price"].Value <decimal>();
                fx.PurchaseTime = DateTime.Parse(trdOpnItem["openTime"].Value <string>());
                fx.TradeId      = trdOpnItem["id"].Value <int>();
                SaveExtrapolateBuyData(fx);
            }
        }
Exemple #10
0
        public bool UpdateFxStockDetails(JToken jToken, ForexData fxS)
        {
            bool rtnVal = false;

            //lock (fxLock)
            //{
            try
            {
                JObject ordCrtObject = jToken["orderCreateTransaction"].Value <JObject>();
                JToken  tkFill       = jToken["orderFillTransaction"];

                if (tkFill == null)
                {
                    JObject ordCancelObject = jToken["orderCancelTransaction"].Value <JObject>() == null ? null : jToken["orderCancelTransaction"].Value <JObject>();
                }
                else
                {
                    JObject ordFillObject = jToken["orderFillTransaction"].Value <JObject>();
                    if (ordFillObject["type"].Value <string>() == "ORDER_FILL")
                    {
                        fxS.Count        = ordFillObject["units"].Value <decimal>();
                        fxS.PriceSell    = ordFillObject["price"].Value <decimal>();
                        fxS.FeeSell      = ordFillObject["financing"].Value <decimal>();
                        fxS.ProfitnLoss  = ordFillObject["pl"].Value <decimal>();
                        fxS.ModifiedTime = DateTime.Parse(ordFillObject["time"].Value <string>());
                        //JArray clsTrades = ordFillObject["tradesClosed"].Value<JArray>();
                        //if (clsTrades!=null)
                        //{

                        //}
                        rtnVal = true;
                    }
                    //else
                    //    ord.Status = "PENDING";
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            // }
            return(rtnVal);
        }
Exemple #11
0
 protected virtual void AddImportRow(DateTime updateTime, ForexData data, 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     = data.code;
     importRow.volume        = 0;
     importRow.closePrice    = data.last;
     //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();
     }
 }
        public override IEnumerable <TradeData> GetOpenTrades(string symbol, string accountId)
        {
            string           method  = string.Empty;
            List <ForexData> result  = null;
            ForexData        fxStock = null;

            if (symbol != string.Empty)
            {
                method = EndPoints.LIST_OPEN_TRADES;
            }
            else
            {
                method = EndPoints.LIST_ALL_OPEN_TRADES;
            }

            var argsParam = "instrument=" + symbol + "&state=OPEN";

            method = method.Replace("{accountId}", accountId);

            string jsonResult = ApiClient.CallAsync(this.GetExchangeName(), Methods.GET,
                                                    method, false, argsParam).Result;

            if (jsonResult != string.Empty)
            {
                JObject jsonObject = JObject.Parse(jsonResult);
                JArray  trdArray   = jsonObject["trades"].Value <JArray>();

                result = new List <ForexData>();
                foreach (JObject item in trdArray)
                {
                    fxStock = converter.DeserializeObject <ForexData>(item);
                    result.Add(fxStock);
                }
            }
            return(result);
        }
Exemple #13
0
        private void GetHpData(ForexData forexData, char dealType, int tp, int sl, out int? hp, out long? hp_date)
        {
            int tpMinDelta = TestParameters.GetTpSlMinDelta(m_cp.MainSymbol);
            int slMinDelta = TestParameters.GetTpSlMinDelta(m_cp.MainSymbol);

            int d = dealType == 'B' ? 0 : 1;
            var hps = (sbyte?[, ,])forexData[0];
            var hp_dates = (long?[, ,])forexData[1];

            //WekaUtils.Instance.WriteLog(string.Format("{0}, {1}, {2}, {3}", tp, sl, hps.GetLength(1), hps.GetLength(2)));

            int tpIdx = tp / tpMinDelta - 1;
            int slIdx = sl / slMinDelta - 1;
            if (tpIdx < 0 || tpIdx > hps.GetLength(1)
                || slIdx < 0 || slIdx > hps.GetLength(2))
            {
                throw new AssertException(string.Format("hps length is {0}*{1}, get tp={2}, sl={3}", hps.GetLength(1), hps.GetLength(2), tp, sl));
            }
            hp = hps[d, tpIdx, slIdx];
            hp_date = hp_dates[d, tp / tpMinDelta - 1, sl / slMinDelta - 1];
        }
Exemple #14
0
        public T DeserializeObject <T>(JToken jToken)
        {
            T obj = default(T);

            //lock (dzLock)
            //{
            try
            {
                Type type = typeof(T);
                if (type.Name == "Quote")
                {
                    //List<Quote> qList = new List<Quote>();
                    Quote q = new Quote();
                    q.Symbol = jToken["name"].Value <string>();
                    //qList.Add(q);
                    obj = (T)Convert.ChangeType(q, typeof(T));
                }
                else if (type.Name == "OandaAccount")
                {
                    JObject      accObject = jToken["account"].Value <JObject>();
                    OandaAccount a         = new OandaAccount();
                    a.Id              = accObject["id"].Value <string>();
                    a.Balance         = accObject["balance"].Value <decimal>();
                    a.MarginAvailable = accObject["marginAvailable"].Value <decimal>();

                    JArray        posArray = accObject["positions"].Value <JArray>();
                    ForexPosition p        = null;
                    foreach (JObject item in posArray)
                    {
                        JObject longObj = item["long"].Value <JObject>();
                        if (longObj["units"].Value <decimal>() > 0)
                        {
                            p              = new ForexPosition();
                            p.Symbol       = item["instrument"].Value <string>();
                            p.AccountId    = a.Id;
                            p.TotalCount   = longObj["units"].Value <decimal>();
                            p.AveragePrice = longObj["averagePrice"].Value <decimal>();
                            p.UnrealizedPL = longObj["unrealizedPL"].Value <decimal>();

                            JArray tradeArray = longObj["tradeIDs"].Value <JArray>();
                            foreach (JValue subItem in tradeArray)
                            {
                                p.TradeIdList.Add(subItem.ToString());
                            }
                            a.PositionList.Add(p);
                        }
                        JObject shortObj = item["short"].Value <JObject>();
                        if (shortObj["units"].Value <decimal>() < 0)
                        {
                            p              = new ForexPosition();
                            p.Symbol       = item["instrument"].Value <string>();
                            p.AccountId    = a.Id;
                            p.TotalCount   = shortObj["units"].Value <decimal>();
                            p.AveragePrice = shortObj["averagePrice"].Value <decimal>();
                            p.UnrealizedPL = shortObj["unrealizedPL"].Value <decimal>();

                            JArray tradeArray = shortObj["tradeIDs"].Value <JArray>();
                            foreach (JValue subItem in tradeArray)
                            {
                                p.TradeIdList.Add(subItem.ToString());
                            }
                            a.PositionList.Add(p);
                        }
                    }
                    JArray    trdArray = accObject["trades"].Value <JArray>();
                    string    sym      = string.Empty;
                    ForexData fx       = null;
                    foreach (JObject trdItem in trdArray)
                    {
                        fx = new ForexData();
                        if (sym != trdItem["instrument"].Value <string>())
                        {
                            sym = trdItem["instrument"].Value <string>();
                            p   = (ForexPosition)a.PositionList.Find(pos => pos.Symbol == sym);
                        }
                        fx.AccountId    = a.Id;
                        fx.Symbol       = trdItem["instrument"].Value <string>();
                        fx.Count        = trdItem["currentUnits"].Value <decimal>();
                        fx.PriceBuy     = trdItem["price"].Value <decimal>();
                        fx.PurchaseTime = DateTime.Parse(trdItem["openTime"].Value <string>());
                        fx.UnrealizedPL = trdItem["unrealizedPL"].Value <decimal>();
                        fx.TradeId      = trdItem["id"].Value <int>();
                        p.TradeList.Add(fx);
                    }
                    JArray ordArray = accObject["orders"].Value <JArray>();
                    foreach (JObject ordItem in ordArray)
                    {
                    }
                    a.LastTransactionId = jToken["lastTransactionID"].Value <string>();
                    obj = (T)Convert.ChangeType(a, typeof(T));
                }
                else if (type.Name == "Order")
                {
                    //decimal execVal = 0.0m;
                    //Order o = new Order();
                    //o.OrderId = jToken["id"].Value<string>();
                    //o.Price = jToken["price"].Value<decimal>();
                    //o.Count = jToken["size"].Value<decimal>();
                    //o.Brokerage = jToken["fill_fees"].Value<decimal>();
                    //o.Cost = jToken["executed_value"].Value<decimal>();
                    //if (jToken["status"].Value<string>() == "done")
                    //{
                    //    o.Status = "ACTIVE";
                    //    o.Settled = jToken["settled"].Value<bool>();
                    //    /* if (jToken["side"].Value<string>() == "buy")
                    //         o.Cost = execVal + o.Brokerage;
                    //     else if (jToken["side"].Value<string>() == "sell")
                    //         o.Cost = execVal - o.Brokerage;*/
                    //    o.DoneAt = jToken["done_at"].Value<DateTime>();
                    //}
                    //else
                    //    o.Status = "ORDER";
                    //obj = (T)Convert.ChangeType(o, typeof(T));
                }
                else if (type.Name == "ForexPosition")
                {
                    ForexPosition p = new ForexPosition();
                    p.Symbol = jToken["instrument"].Value <string>();
                    JObject longObj  = jToken["long"].Value <JObject>();
                    JObject shortObj = jToken["short"].Value <JObject>();

                    if (longObj["units"].Value <decimal>() > 0)
                    {
                        p.TotalCount   = longObj["units"].Value <decimal>();
                        p.AveragePrice = longObj["averagePrice"].Value <decimal>();
                        p.UnrealizedPL = longObj["unrealizedPL"].Value <decimal>();
                    }
                    if (shortObj["units"].Value <decimal>() < 0)
                    {
                        p.TotalCount   = shortObj["units"].Value <decimal>();
                        p.AveragePrice = shortObj["averagePrice"].Value <decimal>();
                        p.UnrealizedPL = shortObj["unrealizedPL"].Value <decimal>();
                    }

                    JArray tradeArray = longObj["tradeIDs"].Value <JArray>();
                    foreach (JValue item in tradeArray)
                    {
                        p.TradeIdList.Add(item.ToString());
                    }

                    obj = (T)Convert.ChangeType(p, typeof(T));
                }
                else if (type.Name == "ForexData")
                {
                    ForexData fx = new ForexData();
                    fx.Symbol       = jToken["instrument"].Value <string>();
                    fx.Count        = jToken["currentUnits"].Value <decimal>();
                    fx.PriceBuy     = jToken["price"].Value <decimal>();
                    fx.PurchaseTime = DateTime.Parse(jToken["openTime"].Value <string>());
                    fx.UnrealizedPL = jToken["unrealizedPL"].Value <decimal>();
                    fx.TradeId      = jToken["id"].Value <int>();

                    obj = (T)Convert.ChangeType(fx, typeof(T));
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            //}
            return(obj);
        }
Exemple #15
0
        protected static ForexData[] ImportForex(string url)
        {
            System.Net.WebRequest  webReq   = System.Net.WebRequest.Create(url);
            System.Net.WebResponse webRes   = webReq.GetResponse();
            System.IO.Stream       mystream = webRes.GetResponseStream();
            if (mystream == null)
            {
                return(null);
            }

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

            int iColumn = 0;
            var myNode  = myHtmlDoc.DocumentNode.SelectNodes("//table[@id='fund_list_table']/tr/td[1]");

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

            if (myNode == null)
            {
                return(null);
            }

            ForexData[] result = new ForexData[0];
            foreach (HtmlNode link in myNode)
            {
                ++iColumn;
                string   att    = link.InnerText;
                HtmlNode thuxem = link.ParentNode;
                String   attt   = thuxem.InnerHtml;
                if (att == "Pair")
                {
                    HtmlNode nodeOfDataRow = link.ParentNode;       //Lấy node tên column
                    nodeOfDataRow = nodeOfDataRow.NextSibling;      // Lấy hàng dữ liệu đầu tiên
                    string asdf = nodeOfDataRow.InnerHtml;

                    while (nodeOfDataRow != null)
                    {
                        HtmlNode      nodeOfRow = nodeOfDataRow.FirstChild; //Lấy ô dữ liệu đầu tiên
                        List <String> row       = new List <string>();
                        while (nodeOfRow != null)                           // Lấy các ô dữ liệu tiếp theo
                        {
                            //Kiem tra xem chuoi co hop le
                            if (!nodeOfRow.InnerText.Contains("<!--") && nodeOfRow.InnerText.Length > 0)
                            {
                                row.Add(nodeOfRow.InnerText);
                            }
                            nodeOfRow = nodeOfRow.NextSibling;
                        }
                        if (row.Count >= 4)
                        {
                            ForexData data = Convert2ForexData(row);
                            if (data != null)
                            {
                                Array.Resize(ref result, result.Length + 1);
                                result[result.Length - 1] = data;
                            }
                        }
                        nodeOfDataRow = nodeOfDataRow.NextSibling;      // Lay Du Lieu Dong Tiep theo
                    }
                }
            }
            return(result);
        }
Exemple #16
0
        public void UpdateAccountChanges(JToken jToken, OandaAccount act)
        {
            //lock (dzLock)
            //{
            ForexPosition pos = null;
            ForexData     fx  = null;

            try
            {
                if (act.LastTransactionId != jToken["lastTransactionID"].Value <string>())
                {
                    act.LastTransactionId = jToken["lastTransactionID"].Value <string>();
                    JObject chgObject      = jToken["changes"].Value <JObject>();
                    JArray  trdOpenArray   = chgObject["tradesOpened"].Value <JArray>();
                    JArray  trdCloseArray  = chgObject["tradesClosed"].Value <JArray>();
                    JArray  posArray       = chgObject["positions"].Value <JArray>();
                    JArray  filledOrdArray = chgObject["ordersFilled"].Value <JArray>();
                    JArray  cancelOrdArray = chgObject["ordersCancelled"].Value <JArray>();
                    act.OpenedTradesJson = trdOpenArray.ToString();
                    foreach (JObject posItem in posArray)
                    {
                        pos = (ForexPosition)act.PositionList.Find(obj => obj.Symbol == posItem["instrument"].Value <string>());
                        if (pos == null) //New position added
                        {
                            pos           = new ForexPosition();
                            pos.AccountId = act.Id;
                            act.PositionList.Add(pos);
                        }
                        pos.Symbol = posItem["instrument"].Value <string>();
                        JObject longObj = posItem["long"].Value <JObject>();
                        if (longObj["units"].Value <decimal>() != 0) //Existing long position updated
                        {
                            pos.TotalCount   = longObj["units"].Value <decimal>();
                            pos.AveragePrice = longObj["averagePrice"].Value <decimal>();

                            JArray tradeArray = longObj["tradeIDs"].Value <JArray>();
                            pos.TradeIdList.Clear();
                            foreach (JValue item in tradeArray)
                            {
                                pos.TradeIdList.Add(item.ToString());
                            }
                        }
                        JObject shortObj = posItem["short"].Value <JObject>();
                        if (shortObj["units"].Value <decimal>() != 0) //Existing short position updated
                        {
                            pos.TotalCount   = shortObj["units"].Value <decimal>();
                            pos.AveragePrice = shortObj["averagePrice"].Value <decimal>();

                            JArray tradeArray = shortObj["tradeIDs"].Value <JArray>();
                            pos.TradeIdList.Clear();
                            foreach (JValue item in tradeArray)
                            {
                                pos.TradeIdList.Add(item.ToString());
                            }
                        }
                        if (longObj["units"].Value <decimal>() == 0 && shortObj["units"].Value <decimal>() == 0) //Existing position closed
                        {
                            act.PositionList.Remove(pos);
                        }
                    }
                    foreach (JObject trdClsItem in trdCloseArray)
                    {
                        var trdId = trdClsItem["id"].Value <int>();
                        pos = (ForexPosition)act.PositionList.Find(obj => obj.Symbol == trdClsItem["instrument"].Value <string>());
                        if (pos != null)
                        {
                            pos.TradeList.Remove(pos.TradeList.Find(tr => tr.TradeId == trdId));
                        }
                    }

                    foreach (JObject trdOpnItem in trdOpenArray)
                    {
                        fx              = new ForexData();
                        fx.Symbol       = trdOpnItem["instrument"].Value <string>();
                        fx.AccountId    = act.Id;
                        fx.Count        = trdOpnItem["currentUnits"].Value <decimal>();
                        fx.PriceBuy     = trdOpnItem["price"].Value <decimal>();
                        fx.PurchaseTime = DateTime.Parse(trdOpnItem["openTime"].Value <string>());
                        fx.TradeId      = trdOpnItem["id"].Value <int>();
                        pos             = (ForexPosition)act.PositionList.Find(obj => obj.Symbol == trdOpnItem["instrument"].Value <string>());
                        pos.TradeList.Add(fx);
                    }
                }


                JObject stObject = jToken["state"].Value <JObject>();
                JArray  trdArray = stObject["trades"].Value <JArray>();
                JArray  pArray   = stObject["positions"].Value <JArray>();

                foreach (JObject psItem in pArray)
                {
                    pos = (ForexPosition)act.PositionList.Find(obj => obj.Symbol == psItem["instrument"].Value <string>());
                    pos.UnrealizedPL = psItem["netUnrealizedPL"].Value <decimal>();
                }
                foreach (JObject tdItem in trdArray)
                {
                    //pos = act.PositionList.Find(obj => obj.Symbol == tdItem["instrument"].Value<string>());
                    //fx = (ForexData) pos.TradeList.Find(obj => obj.Id == tdItem["id"].Value<string>());
                    fx = GetFxStockFromTradeId(act.PositionList, tdItem["id"].Value <int>());
                    if (fx != null)
                    {
                        fx.UnrealizedPL = tdItem["unrealizedPL"].Value <decimal>();
                    }
                    else
                    {
                        Console.WriteLine("Error while getting unrealized profit for trades");
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            // }
        }
Exemple #17
0
 protected virtual void AddImportRow(DateTime updateTime, ForexData data, 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 = data.code;
     importRow.volume = 0;
     importRow.closePrice = data.last;
     //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();
 }
Exemple #18
0
            protected static ForexData Convert2ForexData(List<string> row)
            {
                string[] parts;
                decimal last = 0, high = 0, low = 0, changed = 0;
                //if (!common.system.StrToDecimal(row[1].Trim(), myCulture, out last)) return null;
                parts=row[1].Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                if (!common.system.StrToDecimal(parts[0], myCulture, out last)) return null;

                parts = row[2].Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                if (parts.Length < 2) return null;
                if (!common.system.StrToDecimal(parts[0].Trim(), myCulture, out high)) return null;
                if (!common.system.StrToDecimal(parts[1].Trim(), myCulture, out low)) return null;
                if (!common.system.StrToDecimal(row[3].Trim(), myCulture, out changed)) return null;
                ForexData data = new ForexData();
                data.code = row[0].Replace("/", "").Replace(" ", "");
                data.last = last;
                data.high = high;
                data.low = low;
                data.changed = changed;
                return data;
            }
Exemple #19
0
        private static data.importDS.importPriceDataTable GetPrice(DateTime updateTime, string url, string marketCode)
        {
            data.importDS.importPriceDataTable importPriceTbl = new data.importDS.importPriceDataTable();
            ForexData[] frData = ImportForex(url);
            ForexData goldData = frData[3]; //Gold at price 4
            if (lastForexData != null)
            {
                if (lastForexData.last == goldData.last && 
                    lastForexData.high == goldData.high &&
                    lastForexData.low  == goldData.low) return importPriceTbl;
            }
            else lastForexData = new ForexData();
            lastForexData.last = goldData.last;
            lastForexData.high = goldData.high;
            lastForexData.low = goldData.low;
            
            data.importDS.importPriceRow importRow;
            importRow = importPriceTbl.NewimportPriceRow();
            application.DbAccess.InitData(importRow);
            importRow.onDate = updateTime;
            importRow.stockExchange = marketCode;
            importRow.stockCode = goldData.code;
            importRow.closePrice = goldData.last;
            importRow.highPrice = goldData.high;
            importRow.lowPrice = goldData.low;

            if (goldOpenPriceDate != updateTime.Date || goldOpenPrice == decimal.MinValue)
            {
                data.baseDS.priceDataRow row  = application.DbAccess.GetLastPriceData(importRow.stockCode);
                if (row != null) goldOpenPrice = row.closePrice;
                else  goldOpenPrice = importRow.closePrice;
                goldOpenPriceDate = updateTime.Date;
            }
            importRow.openPrice = goldOpenPrice;
            importPriceTbl.AddimportPriceRow(importRow);
            return importPriceTbl;
        }