Ejemplo n.º 1
0
        //==============================================
        public RealtimeChart(TradeHistory trade, xIEventListener listener)
            : base(listener)
        {
            makeCustomRender(true);

            mContext = Context.getInstance();
            mTrade   = trade;

            mChartXYLength = 4000;
            mChartXYs      = new short[2 * mChartXYLength];

            mCurrentTradeSel = 0;

            setBackgroundColor(C.COLOR_BLACK);

            pBBUppers = new float[10000];
            pBBLowers = new float[10000];
            pTmp      = new float[10000];
            pTmpInt   = new int[5000];

            mPrices  = new float[10000];
            mVolumes = new int[10000];
            mTimes   = new int[10000];

            mButtonMACD = xButton.createStandardButton(0, null, "MACD", 60);
        }
Ejemplo n.º 2
0
        public TradeHistoryTest()
        {
            var raoul  = new Trader("Raoul", "Cambridge", false);
            var mario  = new Trader("Mario", "Milano", true);
            var alan   = new Trader("Alan", "Cambridge", false);
            var brian  = new Trader("Brian", "Cambridge", false);
            var bohous = new Trader("Bohous", "Kladno", false);
            var jarous = new Trader("Jarous", "Kladno", true);

            var transactions = new List <Transaction>
            {
                new Transaction(brian, 2011, 300),
                new Transaction(raoul, 2012, 1000),
                new Transaction(raoul, 2011, 400),
                new Transaction(mario, 2012, 20),
                new Transaction(mario, 2012, 10),
                new Transaction(alan, 2012, 950),
                new Transaction(bohous, 2012, 1000),
                new Transaction(bohous, 2011, 1100),
                new Transaction(bohous, 2012, 800),
                new Transaction(jarous, 2011, 10),
                new Transaction(jarous, 2011, 30)
            };

            _tradeHistory = new TradeHistory(transactions);
        }
Ejemplo n.º 3
0
        public List <TradeHistory> GetHistory(string coin1, string coin2)
        {
            List <TradeHistory> histories = new List <TradeHistory>();

            try
            {
                string     pms  = $"symbol={coin1}{coin2}&size=20";
                HttpClient req  = new HttpClient(TRADE_HISTORY_URL + "?" + pms);
                string     resp = req.GetString();

                JObject jo  = JsonConvert.DeserializeObject <JObject>(resp);
                JArray  arr = (JArray)jo["trades"];
                foreach (var i in arr)
                {
                    TradeHistory his = new TradeHistory();
                    his.ID       = i["tradeId"].ToString();
                    his.Side     = i["take"].ToString();
                    his.Price    = Convert.ToDecimal(i["price"].ToString());
                    his.Quantity = Convert.ToDecimal(i["quantity"].ToString());
                    his.Time     = Utils.ConvertTimestamp2DatetimeShortStr((long)i["time"]);

                    histories.Add(his);
                }
            }
            catch (Exception e)
            {
                Logging.Error(e);
            }

            return(histories);
        }
 private void AddNewTradeHistory(CommissionMessage commissionMessage)
 {
     using (var context = new MyDBContext())
     {
         var executionMessage =
             this.SingleOrDefault <ExecutionMessage>(x => x.ExecutionId == commissionMessage.ExecutionId,
                                                     context);
         if (executionMessage != null)
         {
             var tradeHistory = new TradeHistory
             {
                 ID            = commissionMessage.ID,
                 AccountID     = executionMessage.AccountID,
                 ExecutionID   = executionMessage.ExecutionId,
                 ExecutionTime = executionMessage.Time,
                 Side          = ConvertFromString(executionMessage.Side),
                 Quantity      = executionMessage.Quantity,
                 InstrumentID  = executionMessage.InstrumentID,
                 Price         = executionMessage.Price,
                 Commission    = commissionMessage.Commission,
                 RealizedPnL   = new decimal(commissionMessage.RealizedPnL)
             };
             Add(tradeHistory, context);
             SaveChanges(context);
         }
         else
         {
             Thread.Sleep(1000);
             AddNewTradeHistory(commissionMessage);
         }
     }
 }
Ejemplo n.º 5
0
        private void main_Load_1(object sender, EventArgs e)
        {
            {
                mainUpdater = new MainUpdater(sAPI_Key, sAPI_Secret);

                coinList = mainUpdater.getUpdateList();
                if (coinList.Count < 1)
                {
                    MessageBox.Show("Init error due to API error, try again.");
                    Close();
                    return;
                }
                mainUpdater.updateHoldList();
                holdList = mainUpdater.holdList.Copy();

                for (int i = 0; i < coinList.Count; i++)
                {
                    list_coinName.Items.Add(coinList[i]);
                }

                showHoldList = new DataTable();
                showHoldList.Columns.Add("Name", typeof(string));
                showHoldList.Columns.Add("Units", typeof(double));
                showHoldList.Columns.Add("Value", typeof(double));
                showHoldList.Columns.Add("Total", typeof(double));
            }

            {
                tradeHistory = new TradeHistory(sAPI_Key, sAPI_Secret);
                if (tradeHistory.loadFile() < 0)
                {
                    Close();
                    return;
                }
            }

            {
                macro = new MacroSetting(sAPI_Key, sAPI_Secret, coinList);
                macro.setLastKrw();

                if (macro.loadFile() < 0)
                {
                    Close();
                    return;
                }
            }

            {
                thread_updater      = new Thread(() => executeMainUpdater());
                thread_tradeHistory = new Thread(() => executeTradeHistoryUpdate());
                thread_macro        = new Thread(() => executeMacro());

                thread_updater.Start();
                thread_tradeHistory.Start();
                thread_macro.Start();
            }

            isInit = true;
        }
Ejemplo n.º 6
0
        public override void setSize(int w, int h)
        {
            base.setSize(w, h);

            mButtonMACD.setPosition(getW() - mButtonMACD.getW(), 0);

            mOldTrade = null;   //  force recalc everything
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Retrieves completed trades from /inventoryhistory/
        /// </summary>
        /// <param name="limit">Max number of trades to retrieve</param>
        /// <returns>A List of 'TradeHistory' objects</returns>
        public List <TradeHistory> GetTradeHistory(int limit = 0)
        {
            // most recent trade is first
            List <TradeHistory> TradeHistoryList = new List <TradeHistory>();
            var url  = "http://steamcommunity.com/profiles/" + BotId.ConvertToUInt64() + "/inventoryhistory/";
            var html = RetryWebRequest(SteamWeb, url, "GET", null);
            // TODO: handle rgHistoryCurrency as well
            Regex reg = new Regex("rgHistoryInventory = (.*?)};");
            Match m   = reg.Match(html);

            if (m.Success)
            {
                var json         = m.Groups[1].Value + "}";
                var schemaResult = JsonConvert.DeserializeObject <Dictionary <int, Dictionary <ulong, Dictionary <ulong, GenericInventory.Inventory.Item> > > >(json);
                var trades       = new Regex("HistoryPageCreateItemHover\\((.*?)\\);");
                var tradeMatches = trades.Matches(html);
                foreach (Match match in tradeMatches)
                {
                    if (match.Success)
                    {
                        var tradeHistoryItem = new TradeHistory();
                        tradeHistoryItem.ReceivedItems = new List <Trade.TradeAsset>();
                        tradeHistoryItem.GivenItems    = new List <Trade.TradeAsset>();
                        var historyString    = match.Groups[1].Value.Replace("'", "").Replace(" ", "");
                        var split            = historyString.Split(',');
                        var tradeString      = split[0];
                        var tradeStringSplit = tradeString.Split('_');
                        var tradeNum         = Convert.ToInt32(tradeStringSplit[0].Replace("trade", ""));
                        if (limit > 0 && tradeNum >= limit)
                        {
                            break;
                        }
                        var appId       = Convert.ToInt32(split[1]);
                        var contextId   = Convert.ToUInt64(split[2]);
                        var itemId      = Convert.ToUInt64(split[3]);
                        var amount      = Convert.ToInt32(split[4]);
                        var historyItem = schemaResult[appId][contextId][itemId];
                        var genericItem = new Trade.TradeAsset(appId, contextId, itemId, amount);
                        // given item has ownerId of 0
                        // received item has ownerId of own SteamID
                        if (historyItem.OwnerId == 0)
                        {
                            tradeHistoryItem.GivenItems.Add(genericItem);
                        }
                        else
                        {
                            tradeHistoryItem.ReceivedItems.Add(genericItem);
                        }
                        TradeHistoryList.Add(tradeHistoryItem);
                    }
                }
            }
            return(TradeHistoryList);
        }
Ejemplo n.º 8
0
        public static List <TradeHistory> CycleDownloadData(DateTime _StartDate, DateTime _EndDate, string _Pair)
        {
            SecondPair = _Pair;

            UnixStartDate = (int)(_StartDate - new DateTime(1970, 1, 1)).TotalSeconds;
            UnixEndDate   = (int)(_EndDate - new DateTime(1970, 1, 1)).TotalSeconds;

            SitePath = "https://" + $"poloniex.com/public?command=returnTradeHistory&currencyPair={FirstPair}_{SecondPair}&start={UnixStartDate}&end={UnixEndDate}";

            return(TradeHistory.FromJson(JsonToString.GetString(SitePath, FileName)));
        }
Ejemplo n.º 9
0
        public Dealer(Client client, String currency, XElement config)
        {
            this.client = client;
            this.trade  = new TradeWebSockerTicker(currency);

            this.actualListBuyOrder  = new ActualListOrder("OrderBuyData.xml");//TODO: edit for more Dealers.. file name is the same
            this.actualListSellOrder = new ActualListOrder("OrderSellData.xml");
            this.history             = new TradeHistory("TradeHistory.xml");

            this.productType = Utils.GetProductType(currency);

            SellOnly = false;
        }
Ejemplo n.º 10
0
 public void ClearTradeHistory()
 {
     if (TradeHistory != null)
     {
         TradeHistory.Clear();
     }
     if (ShortTradeHistory != null)
     {
         ShortTradeHistory.Clear();
     }
     if (TradeStatistic != null)
     {
         TradeStatistic.Clear();
     }
 }
Ejemplo n.º 11
0
        public List <TradeHistory> ReadAllHistory()
        {
            var result = new List <TradeHistory>();

            using (SqlConnection conn = new SqlConnection(Conn))
            {
                string cmdText = "SELECT * FROM [Stock].[dbo].[TradeHistory] ";
                conn.Open();
                SqlCommand Cmd = new SqlCommand(cmdText, conn);
                using (System.Data.SqlClient.SqlDataReader oReader = Cmd.ExecuteReader())
                {
                    while (oReader.Read())
                    {
                        TradeHistory tmp = new TradeHistory();
                        int          _t1 = 0;
                        float        _t2 = 0;
                        tmp.ID      = oReader["ID"].ToString();
                        tmp.Symbol  = oReader["Symbol"].ToString();
                        tmp.BuyTime = oReader["BuyTime"].ToString();
                        Int32.TryParse(oReader["BuyCount"].ToString(), out _t1);
                        tmp.BuyCount = _t1;
                        _t1          = 0;
                        float.TryParse(oReader["BuyPrice"].ToString(), out _t2);
                        tmp.BuyPrice = _t2;
                        _t2          = 0;
                        tmp.SellTime = oReader["SellTime"].ToString();
                        Int32.TryParse(oReader["SellCount"].ToString(), out _t1);
                        tmp.SellCount = _t1;
                        _t1           = 0;
                        float.TryParse(oReader["SellPrice"].ToString(), out _t2);
                        tmp.SellPrice = _t2;
                        _t2           = 0;
                        float.TryParse(oReader["Profit"].ToString(), out _t2);
                        tmp.Profit = _t2;
                        _t2        = 0;
                        float.TryParse(oReader["NetValue"].ToString(), out _t2);
                        tmp.NetValue = _t2;
                        _t2          = 0;
                        tmp.Currency = oReader["Currency"].ToString();
                        result.Add(tmp);
                    }

                    conn.Close();
                }
                return(result);
            }
        }
Ejemplo n.º 12
0
        public void setTrade(TradeHistory trade)
        {
            mTrade = trade;

            if (trade == null)
            {
                return;
            }
            mVolumeLabel = "";
            mTimeStart   = "";
            mTimeEnd     = "";

            mPriceBase        = trade.mShare.getRefFromPriceboard();
            trade.mHasNewData = true;

            updateTradeInfo();
        }
Ejemplo n.º 13
0
 protected internal virtual void InsertTradeHistoryItem(TradeInfoItem item)
 {
     if (TradeHistory.Count > 0)
     {
         TradeInfoItem first = TradeHistory.First();
         if (first.Time > item.Time)
         {
             throw new Exception("Invalid Trade History Items Order By Time");
         }
         if (first.Id != 0 && first.Id != item.Id - 1)
         {
             throw new Exception("Invalid Trade History Items Order By Id");
         }
     }
     TradeHistory.AddFirst(item);
     ShortTradeHistory.AddFirst(item);
 }
        public RealtimeTradeListDetail(TradeHistory trade, int w, int h)
        {
            mTrade = trade;
            float[]   columnPercents = { 25, 35, 40 };
            String[]  columnTexts    = { "Giờ", "Giá", "Khối lượng" };
            xListView l = xListView.createListView(null, columnTexts, columnPercents, w, h, Context.getInstance().getImageList(C.IMG_BLANK_ROW_ICON, 1, 21), false);

            l.setID(-1);
            l.setBackgroundColor(C.COLOR_GRAY);
            mList = l;

            for (int i = trade.getTransactionCount() - 1; i >= 0; i--)
            {
                RowOnlineTrade r = RowOnlineTrade.createRowQuoteList(trade, i, null);
                l.addRow(r);
            }

            mLastTime = trade.getLastTime();
        }
Ejemplo n.º 15
0
    protected override void OnStopRunning()
    {
        EntityManager.CompleteAllJobs();

        _tradeAsks.Dispose();
        _tradeBids.Dispose();
        _deltaMoney.Dispose();
        _profitsByLogic.Dispose();
        _bankrupt.Dispose();

        AskHistory.Dispose();
        BidHistory.Dispose();
        TradeHistory.Dispose();
        PriceHistory.Dispose();
        ProfitsHistory.Dispose();
        RatioHistory.Dispose();
        FieldHistory.Dispose();
        _logicEntities.Dispose();
        _goodsMostLogic.Dispose();
    }
        protected virtual TradingResult MarketSell(double rate, double amount)
        {
            TradingResult res = null;

            if (!DemoMode)
            {
                res = Ticker.Sell(rate, amount);
                if (res == null)
                {
                    Log(LogType.Error, "", rate, amount, StrategyOperation.MarketSell);
                }
                return(res);
            }
            else
            {
                res = AddDemoTradingResult(rate, amount, OrderType.Sell);
            }
            TradeHistory.Add(res);
            Log(LogType.Success, "", rate, amount, StrategyOperation.MarketSell);
            return(res);
        }
Ejemplo n.º 17
0
        public void Update(TradeHistory tradeHistory)
        {
            CryptoTradeHistory tradeHistoryRecord = this.userIdentityRepository.FindByCondition(u => u.Login == this.GetUserIdentity())
                                                    .SelectMany(a => a.CryptoTradesHistory)
                                                    .Include(s => s.CurrencySymbol)
                                                    .Include(s => s.CryptoTicker)
                                                    .Single(s => s.Id == tradeHistory.Id);

            if (tradeHistoryRecord == null)
            {
                throw new Exception();
            }

            tradeHistoryRecord.CryptoTickerId   = tradeHistory.CryptoTickerId;
            tradeHistoryRecord.CurrencySymbolId = tradeHistory.CurrencySymbolId;
            tradeHistoryRecord.TradeSize        = tradeHistory.TradeSize;
            tradeHistoryRecord.TradeTimeStamp   = tradeHistory.TradeTimeStamp;
            tradeHistoryRecord.TradeValue       = tradeHistory.TradeValue;

            this.cryptoTradeHistoryRepository.Update(tradeHistoryRecord);
        }
Ejemplo n.º 18
0
        public RowOnlineTrade(xIEventListener listener, TradeHistory trade, int idx)
            : base(listener, TOTAL_COLUMES)
        {
            mContext    = Context.getInstance();
            mTrade      = trade;
            mTradeIndex = idx;

            uint b = C.COLOR_BLACK;
            uint g = C.COLOR_GRAY_DARK;

            uint[] bg = { g, b, b };
            Font   f  = mContext.getFontText();
            Font   fb = mContext.getFontTextB();

            Font[] fs = { f, fb, fb };

            for (int i = 0; i < bg.Length; i++)
            {
                setBackgroundColorForCell(i, bg[i]);
                setTextFont(i, fs[i]);
            }
            //====================
            update();
        }
Ejemplo n.º 19
0
        public override void updateTradeHistory(string marketName, int secondsBack)
        {
            var currentTime = DateTime.UtcNow;
            var end         = Util.getUnixTimestamp(currentTime);
            var start       = end - secondsBack;

            var res    = api.getTradeHistory(marketName, start, end);
            var trades = new List <Trade>();

            foreach (var tkn in res)
            {
                var parsedTimestamp = DateTime.ParseExact((string)tkn["date"], "yyyy-MM-dd HH:mm:ss", null);
                var unixTimeStamp   = Util.getUnixTimestamp(parsedTimestamp);
                var trade           = new Trade((decimal)tkn["amount"], (decimal)tkn["rate"], unixTimeStamp);
                //trade.printDetails();
                trades.Add(trade);
            }
            var hist = new TradeHistory();

            hist.historicalTrades      = trades;
            hist.startTime             = start;
            hist.endTime               = end;
            tradeHistories[marketName] = hist;
        }
Ejemplo n.º 20
0
        static public RowOnlineTrade createRowQuoteList(TradeHistory trade, int idx, xIEventListener listener)
        {
            RowOnlineTrade row = new RowOnlineTrade(listener, trade, idx);

            return(row);
        }
Ejemplo n.º 21
0
        private static void Main(string[] args)
        {
            // Change this.
            const string API_KEY    = "API_KEY";
            const string API_SECRET = "API_SECRET";

            IClientFactory       factory      = new ClientFactory();
            IBtceApiPublicClient publicClient = factory.CreatePublicClient();

            IDictionary <BtcePair, Depth> pairDepths3 = publicClient.GetDepth(new[] { BtcePair.btc_usd });

            foreach (var depth3 in pairDepths3)
            {
                Console.WriteLine("{0}: {1}", depth3.Key, depth3.Value);
            }

            IDictionary <BtcePair, Ticker> pairTickers3 = publicClient.GetTicker(new[] { BtcePair.btc_usd });

            foreach (var ticker3 in pairTickers3)
            {
                Console.WriteLine("{0}: {1}", ticker3.Key, ticker3.Value);
            }

            IDictionary <BtcePair, IEnumerable <TradeInfo> > pairTrades3 = publicClient.GetTrades(new[] { BtcePair.btc_usd });

            foreach (var pairTrade3 in pairTrades3)
            {
                foreach (TradeInfo trade3 in pairTrade3.Value)
                {
                    Console.WriteLine(trade3);
                }
            }

            Ticker ticker = publicClient.GetTicker(BtcePair.btc_usd);

            Console.WriteLine(ticker);
            IEnumerable <TradeInfo> trades = publicClient.GetTrades(BtcePair.btc_usd);

            foreach (TradeInfo trade in trades)
            {
                Console.WriteLine(trade);
            }

            IBtceApiClient client = factory.CreateClient(API_KEY, API_SECRET);

            Depth btcusdDepth = publicClient.GetDepth(BtcePair.usd_rur);

            Console.WriteLine(btcusdDepth);
            decimal fee = publicClient.GetFee(BtcePair.usd_rur);

            Console.WriteLine(fee);

            try
            {
                UserInfo info = client.GetInfo();
                Console.WriteLine(info);
                TransHistory transHistory = client.GetTransHistory();
                Console.WriteLine(transHistory);
                TradeHistory tradeHistory = client.GetTradeHistory(count: 20);
                Console.WriteLine(tradeHistory);
                //// var orderList = btceApi.GetOrderList();  ** DEPRICATED ** use GetActiveOrders() instead!
                OrderList orderList = client.GetActiveOrders();
                Console.WriteLine(orderList);
                TradeAnswer tradeAnswer = client.Trade(BtcePair.btc_usd, TradeType.Sell, 2500, 0.1m);
                Console.WriteLine(tradeAnswer);
                CancelOrderAnswer cancelAnswer = client.CancelOrder(tradeAnswer.OrderId);
                Console.WriteLine(cancelAnswer);
            }
            catch (BtceException e)
            {
                Console.WriteLine("An exception occured: {0}", e);
            }

            Console.WriteLine("Press any key to stop...");
            Console.ReadKey();
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Manually validate if a trade offer went through by checking /inventoryhistory/
        /// You shouldn't use this since it may be exploitable. I'm keeping it here in case I want to rework this in the future.
        /// </summary>
        /// <param name="tradeOffer">A 'TradeOffer' object</param>
        /// <returns>True if the trade offer was successfully accepted, false if otherwise</returns>
//        public bool ValidateTradeAccept(TradeOffer tradeOffer)
//        {
//            try
//            {
//                var history = GetTradeHistory();
//                foreach (var completedTrade in history)
//                {
//                    if (tradeOffer.ItemsToGive.Length == completedTrade.GivenItems.Count && tradeOffer.ItemsToReceive.Length == completedTrade.ReceivedItems.Count)
//                    {
//                        var numFoundGivenItems = 0;
//                        var numFoundReceivedItems = 0;
//                        var foundItemIds = new List<ulong>();
//                        foreach (var historyItem in completedTrade.GivenItems)
//                        {
//                            foreach (var tradeOfferItem in tradeOffer.ItemsToGive)
//                            {
//                                if (tradeOfferItem.ClassId == historyItem.ClassId && tradeOfferItem.InstanceId == historyItem.InstanceId)
//                                {
//                                    if (!foundItemIds.Contains(tradeOfferItem.AssetId))
//                                    {
//                                        foundItemIds.Add(tradeOfferItem.AssetId);
//                                        numFoundGivenItems++;
//                                    }
//                                }
//                            }
//                        }
//                        foreach (var historyItem in completedTrade.ReceivedItems)
//                        {
//                            foreach (var tradeOfferItem in tradeOffer.ItemsToReceive)
//                            {
//                                if (tradeOfferItem.ClassId == historyItem.ClassId && tradeOfferItem.InstanceId == historyItem.InstanceId)
//                                {
//                                    if (!foundItemIds.Contains(tradeOfferItem.AssetId))
//                                    {
//                                        foundItemIds.Add(tradeOfferItem.AssetId);
//                                        numFoundReceivedItems++;
//                                    }
//                                }
//                            }
//                        }
//                        if (numFoundGivenItems == tradeOffer.ItemsToGive.Length && numFoundReceivedItems == tradeOffer.ItemsToReceive.Length)
//                        {
//                            return true;
//                        }
//                    }
//                }
//            }
//            catch (Exception ex)
//            {
//                Console.WriteLine("Error validating trade:");
//                Console.WriteLine(ex);
//            }
//            return false;
//        }

        /// <summary>
        /// Retrieves completed trades from /inventoryhistory/
        /// </summary>
        /// <param name="limit">Max number of trades to retrieve</param>
        /// <param name="numPages">How many pages to retrieve</param>
        /// <returns>A List of 'TradeHistory' objects</returns>
        public List <TradeHistory> GetTradeHistory(int limit = 0, int numPages = 1)
        {
            var tradeHistoryPages = new Dictionary <int, TradeHistory[]>();

            for (var i = 0; i < numPages; i++)
            {
                var tradeHistoryPageList = new TradeHistory[30];
                try
                {
                    var url  = "http://steamcommunity.com/profiles/" + _botId.ConvertToUInt64() + "/inventoryhistory/?p=" + i;
                    var html = RetryWebRequest(_steamWeb, url, "GET", null);
                    // TODO: handle rgHistoryCurrency as well
                    var reg = new Regex("rgHistoryInventory = (.*?)};");
                    var m   = reg.Match(html);
                    if (m.Success)
                    {
                        var json         = m.Groups[1].Value + "}";
                        var schemaResult = JsonConvert.DeserializeObject <Dictionary <int, Dictionary <ulong, Dictionary <ulong, TradeHistory.HistoryItem> > > >(json);
                        var trades       = new Regex("HistoryPageCreateItemHover\\((.*?)\\);");
                        var tradeMatches = trades.Matches(html);
                        foreach (Match match in tradeMatches)
                        {
                            if (!match.Success)
                            {
                                continue;
                            }
                            var historyString    = match.Groups[1].Value.Replace("'", "").Replace(" ", "");
                            var split            = historyString.Split(',');
                            var tradeString      = split[0];
                            var tradeStringSplit = tradeString.Split('_');
                            var tradeNum         = Convert.ToInt32(tradeStringSplit[0].Replace("trade", ""));
                            if (limit > 0 && tradeNum >= limit)
                            {
                                break;
                            }
                            if (tradeHistoryPageList[tradeNum] == null)
                            {
                                tradeHistoryPageList[tradeNum] = new TradeHistory();
                            }
                            var tradeHistoryItem = tradeHistoryPageList[tradeNum];
                            var appId            = Convert.ToInt32(split[1]);
                            var contextId        = Convert.ToUInt64(split[2]);
                            var itemId           = Convert.ToUInt64(split[3]);
                            var amount           = Convert.ToInt32(split[4]);
                            var historyItem      = schemaResult[appId][contextId][itemId];
                            if (historyItem.OwnerId == 0)
                            {
                                tradeHistoryItem.ReceivedItems.Add(historyItem);
                            }
                            else
                            {
                                tradeHistoryItem.GivenItems.Add(historyItem);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error retrieving trade history:");
                    Console.WriteLine(ex);
                }
                tradeHistoryPages.Add(i, tradeHistoryPageList);
            }
            return(tradeHistoryPages.Values.SelectMany(tradeHistoryPage => tradeHistoryPage).ToList());
        }
Ejemplo n.º 23
0
        void drawCandle(xGraphics g, int x, int y0, int w, int h)
        {
            Share share = mShare;

            int  y = 0;
            Font f = mContext.getFontSmall();

            uint color;

            stPriceboardState ps = mContext.mPriceboard.getPriceboard(share.getID());

            if (ps == null)
            {
                return;
            }

            TradeHistory trade = mContext.getTradeHistory(share.getID());
            float        price = ps.getCurrentPrice();
            float        open  = price;//ps.getRef(); //  should be open - testing

            if (trade != null && trade.getTransactionCount() > 0)
            {
                open = trade.getPrice(0);
            }
            else
            {
                open = mContext.mPriceboard.getOpen(mShare.mID);
            }

            if (open != 0 && mContext.mPriceboard.getOpen(mShare.mID) == 0 && !share.isIndex())
            {
                mContext.mPriceboard.setOpen(mShare.mID, (int)open);
            }

            float hi       = ps.getMax();
            float lo       = ps.getMin();
            float priceLen = hi - lo;

            float reference = ps.getRef();
            float min       = ps.getFloor() - (float)reference / 30;
            float max       = ps.getCe() + (float)reference / 30;

            if (share.isIndex())
            {
                price     = trade.mClose / 10.0f;
                open      = trade.mOpen / 10.0f;
                reference = trade.mPriceRef / 10.0f;
                hi        = trade.mHighest / 10.0f;
                lo        = trade.mLowest / 10.0f;
                min       = reference - reference / 40;
                max       = reference + reference / 40;

                if (min > lo)
                {
                    min = lo;
                }
                if (max < hi)
                {
                    max = hi;
                }

                priceLen = (int)(hi - lo);
            }

            if (price == 0)
            {
                return;
            }

            //if (min > ps.getMin() && ps.getMin() > 0) min = ps.getMin();
            //if (max < ps.getMax()) max = ps.getMax();

            float totalPrice = (max - min);  //(10%);

            if (totalPrice < priceLen)
            {
                totalPrice = priceLen;
            }

            if (totalPrice == 0)
            {
                return;
            }

            float ry = (float)(h) / totalPrice;

            int           totalH = (int)(ry * totalPrice);
            int           bodyW  = w / 3;
            StringBuilder sb     = Utils.getSB();

            //================frame=============================
            //  line ref
            g.setColor(0x30ffff00);
            y = (int)(y0 + totalH - (reference - min) * ry);
            g.drawLineDotHorizontal(1, y, getW() - 2, y);
            g.setColor(0xa0ffff00);

/*
 *          if (mDrawRefLabel)
 *          {
 *              sb.AppendFormat("{0:F1}", (float)reference / 10);
 *              g.drawString(f, sb.ToString(), 1, y - f.Height / 2, 0);
 *          }
 */
            //  CE line
            if (!share.isIndex())
            {
                g.setColor(0x30ff00ff);
                y = (int)(y0 + totalH - (ps.getCe() - min) * ry);
                g.drawLineDotHorizontal(1, y, getW() - 2, y);
                g.setColor(0xa0ff00ff);
                sb.Length = 0;
                sb.AppendFormat("{0:F1}", (float)(ps.getCe() / 10));

                if (mDrawRefLabel)
                {
                    g.drawString(f, sb.ToString(), 1, y, 0);
                }

                //  FLOOR line
                g.setColor(0x3000FFFF);
                y = (int)(y0 + totalH - (ps.getFloor() - min) * ry);
                g.drawLineDotHorizontal(1, y, getW() - 2, y);
                g.setColor(0xa000FFFF);
                sb.Length = 0;
                sb.AppendFormat("{0:F1}", (float)(ps.getFloor() / 10));
                if (mDrawRefLabel)
                {
                    g.drawString(f, sb.ToString(), 1, y - f.Height, 0);
                }
            }
            //===================================================
            color = price < open? C.COLOR_RED:C.COLOR_GREEN;
            if (price == open)
            {
                color = C.COLOR_WHITE;
            }
            if (price == 0)
            {
                return;
            }
            //  draw shadow
            g.setColor(C.COLOR_WHITE);
            x = getW() / 2;

            if (share.isIndex() && hi > 0 && lo > 0)
            {
                int minY = (int)(y0 + totalH - (lo - min) * ry);
                int maxY = (int)(y0 + totalH - (hi - min) * ry);

                g.drawLine(x, maxY, x, minY);
            }
            int centerX = x + bodyW / 2;
            //  candle's body
            int oY = (int)(y0 + totalH - (open - min) * ry);
            int cY = (int)(y0 + totalH - (price - min) * ry);

            y = oY < cY?oY:cY;
            int bodyH = Utils.ABS_INT(cY - oY);

            if (bodyH < 2)
            {
                bodyH = 2;
            }
            g.setColor(color);
            g.fillRect(x - bodyW / 2, y, bodyW, bodyH);

            /*
             * if (lo > 0 && lo != open && lo != price)
             * {
             *  y = (int)(y0 + totalH - (lo - min)*ry);
             *  g.setColor(C.COLOR_WHITE);
             *  sb.Length = 0;
             *  sb.AppendFormat("{0:F1}", (float)lo/10);
             *  g.drawString(f, sb.ToString(), centerX - 44, y + 1, 0);
             * }
             * if (hi > 0 && hi != open && hi != price)
             * {
             *  y = (int)(y0 + totalH - (hi - min)*ry);
             *  g.setColor(C.COLOR_WHITE);
             *  sb.Length = 0;
             *  sb.AppendFormat("{0:F1}", (float)hi/10);
             *  g.drawString(f, sb.ToString(), centerX - 44, y - f.Height, 0);
             * }
             * //  2 lines
             * g.setColor(C.COLOR_WHITE);
             * sb.Length = 0;
             * sb.AppendFormat("{0:F1}", (float)open/10);
             *
             * //  open
             * if (oY < cY)
             *  y = oY - f.Height;
             * else
             *  y = oY + 1;
             * if (y < 0) y = 0;
             * if (y + f.Height > getH())
             *  y = getH() - f.Height;
             * g.drawString(f, sb.ToString(), x + bodyW / 2, y, 0);
             * //  price
             * sb.Length = 0;
             * sb.AppendFormat("{0:F1}", (float)price/10);
             * if (cY < oY)
             *  y = cY - f.Height;
             * else
             *  y = cY + 1;
             * if (y < 0) y = 0;
             * if (y + f.Height > getH())
             *  y = getH() - f.Height;
             * g.drawString(f, sb.ToString(), x + bodyW / 2, y, 0);
             */
        }
Ejemplo n.º 24
0
        void drawCandle(xGraphics g, int x, int y0, int w, int h)
        {
            Share share = mShare;

            int  y = 0;
            Font f = mContext.getFontSmall();

            uint color;

            stPriceboardState ps = mContext.mPriceboard.getPriceboard(share.getID());

            if (ps == null)
            {
                return;
            }

            TradeHistory trade = mContext.getTradeHistory(share.getID());
            float        price = ps.getCurrentPrice();
            float        open  = mContext.mPriceboard.getOpen(ps.getID());

            if (trade != null && trade.getTransactionCount() > 0)
            {
                open = trade.getPrice(0);
            }
            else
            {
                open = mContext.mPriceboard.getOpen(mShare.mID);
            }

            if (open != 0 && mContext.mPriceboard.getOpen(mShare.mID) == 0 && !share.isIndex())
            {
                mContext.mPriceboard.setOpen(mShare.mID, (int)open);
            }

            float hi = ps.getMax();
            float lo = ps.getMin();

            //  check hi/lo valid
            if ((hi == 0 || lo == 0))
            {
                float[] hl = new float[2];
                if (trade.getHiLo(hl))
                {
                    if (hi == 0)
                    {
                        hi = hl[0];
                    }
                    if (lo == 0)
                    {
                        lo = hl[1];
                    }
                }
            }

            if (hi == 0)
            {
                hi = open > price ? open : price;
            }
            if (lo == 0)
            {
                lo = open < price ? open : price;
            }
            if (lo == 0)
            {
                lo = hi;
            }
            //---------------------------------------------
            float priceLen = hi - lo;
            float reference = ps.getRef();
            float min, max;

            if (share.isIndex())
            {
                stPriceboardStateIndex pi = mContext.mPriceboard.getPriceboardIndexOfMarket(mShare.getMarketID());
                price = pi.current_point;

                min = lo - price / 40;
                max = hi + price / 40;
            }
            else
            {
                min = ps.getFloor() - reference / 30;
                max = ps.getCe() + reference / 30;
            }

            if (price == 0)
            {
                return;
            }

            //if (min > ps.getMin() && ps.getMin() > 0) min = ps.getMin();
            //if (max < ps.getMax()) max = ps.getMax();

            float totalPrice = (max - min);  //(10%);

            if (totalPrice < priceLen)
            {
                totalPrice = priceLen;
            }

            if (totalPrice == 0)
            {
                return;
            }

            float ry = (float)(h) / totalPrice;

            int           totalH = (int)(ry * totalPrice);
            int           bodyW  = w / 3;
            StringBuilder sb     = Utils.getSB();

            //================frame=============================
            //  line ref
            g.setColor(0x30ffff00);
            y = (int)(y0 + totalH - (reference - min) * ry);
            g.drawLineDotHorizontal(1, y, getW() - 2, y);
            g.setColor(0xa0ffff00);
            if (mDrawRefLabel)
            {
                sb.AppendFormat("{0:F2}", reference);
                g.drawString(f, sb.ToString(), 1, y - f.Height / 2, 0);
            }
            //  CE line
            if (!share.isIndex())
            {
                g.setColor(0x30ff00ff);
                y = (int)(y0 + totalH - (ps.getCe() - min) * ry);
                g.drawLineDotHorizontal(1, y, getW() - 2, y);
                g.setColor(0xa0ff00ff);
                sb.Length = 0;
                sb.AppendFormat("{0:F2}", ps.getCe());

                if (mDrawRefLabel)
                {
                    g.drawString(f, sb.ToString(), 1, y, 0);
                }

                //  FLOOR line
                g.setColor(0x3000FFFF);
                y = (int)(y0 + totalH - (ps.getFloor() - min) * ry);
                g.drawLineDotHorizontal(1, y, getW() - 2, y);
                g.setColor(0xa000FFFF);
                sb.Length = 0;
                sb.AppendFormat("{0:F2}", ps.getFloor());
                if (mDrawRefLabel)
                {
                    g.drawString(f, sb.ToString(), 1, y - f.Height, 0);
                }
            }
            //===================================================
            color = price < open? C.COLOR_RED:C.COLOR_GREEN;
            if (price == open)
            {
                color = C.COLOR_WHITE;
            }
            if (price == 0)
            {
                return;
            }
            //  draw shadow
            g.setColor(C.COLOR_WHITE);
            x = getW() / 2;

            if (hi > 0 && lo > 0)
            {
                int minY = (int)(y0 + totalH - (lo - min) * ry);
                int maxY = (int)(y0 + totalH - (hi - min) * ry);

                g.drawLine(x, maxY, x, minY);
            }
            int centerX = x;
            //  candle's body
            int oY = (int)(y0 + totalH - (open - min) * ry);
            int cY = (int)(y0 + totalH - (price - min) * ry);

            y = oY < cY?oY:cY;
            int bodyH = Utils.ABS_INT(cY - oY);

            if (bodyH < 2)
            {
                bodyH = 2;
            }
            g.setColor(color);
            g.fillRect(x - bodyW / 2, y, bodyW, bodyH);

            if (lo > 0 && lo != open && lo != price)
            {
                y = (int)(y0 + totalH - (lo - min) * ry);
                g.setColor(C.COLOR_YELLOW);
                sb.Length = 0;
                sb.AppendFormat("{0:F2}", lo);
                g.drawString(f, sb.ToString(), centerX - 10, y + 1, 0);
            }
            if (hi > 0 && hi != open && hi != price)
            {
                y = (int)(y0 + totalH - (hi - min) * ry);
                g.setColor(C.COLOR_YELLOW);
                sb.Length = 0;
                sb.AppendFormat("{0:F2}", hi);
                g.drawString(f, sb.ToString(), centerX - 10, y - f.Height, 0);
            }
            //  2 lines
            g.setColor(C.COLOR_WHITE);
            sb.Length = 0;
            sb.AppendFormat("{0:F2}", open);

            //  open
            if (oY < cY)
            {
                y = oY - f.Height;
            }
            else
            {
                y = oY + 1;
            }
            if (y < 0)
            {
                y = 0;
            }
            if (y + f.Height > getH())
            {
                y = getH() - f.Height;
            }
            g.drawString(f, sb.ToString(), x + bodyW / 2, y, 0);
            //  price
            sb.Length = 0;
            sb.AppendFormat("{0:F2}", price);
            if (cY < oY)
            {
                y = cY - f.Height;
            }
            else
            {
                y = cY + 1;
            }
            if (y < 0)
            {
                y = 0;
            }
            if (y + f.Height > getH())
            {
                y = getH() - f.Height;
            }
            g.drawString(f, sb.ToString(), x + bodyW / 2, y, 0);
        }
Ejemplo n.º 25
0
        public IndexControl(xIEventListener listener, int marketID, int w, int h)
            : base(listener)
        {
            mMarketID = marketID;
            mContext  = Context.getInstance();
            setSize(w, h);

            //setBackgroundColor(0xffff0000);

            mTab = new xTabControl();
            addControl(mTab);

            mTab.setSize(w, h);

            TabControl tc = (TabControl)mTab.getControl();

            tc.Selected += new TabControlEventHandler(tabControlSelected);

            int y = 0;

            for (int i = 0; i < TAB_TITLE.Length; i++)
            {
                xTabPage page = new xTabPage(TAB_TITLE[i]);
                mTab.addPage(page);

                if (i == 0)
                {
                    stPriceboardStateIndex pi    = mContext.mPriceboard.getPriceboardIndexOfMarket(marketID);
                    TradeHistory           trade = mContext.getTradeHistory(pi.id);

                    //  realtime
                    RealtimeChart rc = new RealtimeChart(trade, this);
                    h = getH() - y;
                    rc.setPosition(0, y);
                    rc.setSize(w, h);
                    page.addControl(rc);

                    mRealtimeChart = rc;
                    mCurrentChart  = mRealtimeChart;
                }
            }

            int currentTab = mContext.getMarketControlTab(mMarketID);

            if (currentTab < 0 || currentTab >= TAB_INDEX.Length)
            {
                currentTab = 0;
            }
            if (currentTab != -1)
            {
                ((TabControl)mTab.getControl()).SelectedIndex = currentTab;

                onPageSelected(currentTab);
            }

            /*
             * //  Do thi phien
             *
             * int[] ids = {ID_ONLINE_CHART, ID_MONEY_CHART, ID_VOLUMN_CHART, ID_HIS_CHART};
             * int x = 0;
             * int y = 0;
             * int bw = (w / 4) - 2;
             * for (int i = 0; i < text.Length; i++)
             * {
             *  bt = xButton.createStandardButton(ids[i], this, text[i], bw);
             *  bt.setPosition(x, 0);
             *
             *  addControl(bt);
             *  x = bt.getRight() + 2;
             *  y = bt.getBottom() + 4;
             * }
             */
        }
Ejemplo n.º 26
0
        public void showDetailRealtimeChart(TradeHistory trade)
        {
            Share share = trade.saveToShare();

            createNewHistory(share);
        }
Ejemplo n.º 27
0
        public HttpResponseMessage BuyStocks(long UserId, string NameorCode, int Number)
        {
            User            user            = db.Users.FirstOrDefault(s => s.Id == UserId);
            StockAccount    stockAccount    = db.StockAccounts.FirstOrDefault(s => s.UserId == UserId);
            SimulationStock simulationStock = null;
            JObject         jObject         = null;
            ParamHelper     paramHelper     = new ParamHelper();
            string          StockCode       = NameorCode;

            if (paramHelper.HaveEnglish(StockCode) || paramHelper.HaveHanZi(StockCode))
            {
                Stock tempStock = db.Stocks.FirstOrDefault(s => s.StockName == StockCode || s.StockName.Equals(StockCode));
                if (tempStock == null)
                {
                    return(ApiResponse.BadRequest("未找到数据"));
                }
                StockCode = tempStock.StockCode;
            }
            try
            {
                string res = new ShowApiRequest("http://route.showapi.com/131-46", "138438", "dd520f20268747d4bbda22ac31c9cbdf")
                             .addTextPara("stocks", StockCode)
                             .addTextPara("needIndex", "0")
                             .post();
                jObject = JsonConvert.DeserializeObject <JObject>(res);
                if (jObject["showapi_res_body"]["ret_code"].ToString() != "0" || jObject["showapi_res_body"]["list"].Count() == 0)
                {
                    return(ApiResponse.BadRequest("未找到数据"));
                }
                double nowPrice  = Double.Parse(jObject["showapi_res_body"]["list"].First["nowPrice"].ToString());
                string stockName = jObject["showapi_res_body"]["list"].First["name"].ToString();
                if (Number * nowPrice > stockAccount.ValidMoney)
                {
                    return(ApiResponse.BadRequest("老铁,您的钱好像有点不够"));
                }
                else
                {
                    simulationStock = new SimulationStock()
                    {
                        StockAccount   = stockAccount,
                        StockAccountId = stockAccount.Id,
                        StockCode      = StockCode,
                        BuyPrice       = nowPrice,
                        NowPrice       = nowPrice,
                        StockNumber    = Number,
                        StockName      = stockName,
                        BuyTime        = DateTime.Now,
                        Valid          = true
                    };
                    stockAccount.ValidMoney   -= Number * nowPrice;
                    stockAccount.SumStockValue = nowPrice * Number;
                    db.SimulationStocks.Add(simulationStock);
                    db.Entry(stockAccount).State = EntityState.Modified;
                    TradeHistory tradeHistory = new TradeHistory()
                    {
                        StockName         = stockName,
                        StockCode         = StockCode,
                        StockAccountId    = stockAccount.Id,
                        TransactionValue  = nowPrice * Number,
                        TransactionPrice  = nowPrice,
                        TransactionAmount = Number,
                        TransactionType   = Enums.TransactionType.买入,
                        TradeTime         = DateTime.Now
                    };
                    db.TradeHistories.Add(tradeHistory);
                    db.SaveChanges();
                    Thread.Sleep(1);
                }
                Thread.Sleep(1);
            }
#pragma warning disable CS0168 // 声明了变量“ex”,但从未使用过
            catch (Exception ex)
#pragma warning restore CS0168 // 声明了变量“ex”,但从未使用过
            {
                db.Entry(stockAccount).State = EntityState.Unchanged;
                return(ApiResponse.BadRequest("未找到数据"));
            }
            return(ApiResponse.Ok(new
            {
                simulationStock.BuyPrice,
                simulationStock.StockName,
                simulationStock.StockCode,
                simulationStock.StockNumber,
                StockSum = simulationStock.BuyPrice * simulationStock.StockNumber,
                stockAccount.ValidMoney,
                message = "您买入 " + simulationStock.StockName + "(" + simulationStock.StockCode + ") " + Number + "股"
            }));
        }
Ejemplo n.º 28
0
        public HttpResponseMessage SellStocks(long UserId, long SimulationStockId, int SellNumber)
        {
            User            user               = db.Users.FirstOrDefault(s => s.Id == UserId);
            StockAccount    stockAccount       = db.StockAccounts.FirstOrDefault(s => s.UserId == UserId);
            Double          Initial_ValidMoney = stockAccount.ValidMoney;
            SimulationStock simulationStock    = db.SimulationStocks.FirstOrDefault(s => s.Id == SimulationStockId);

            if (SellNumber > simulationStock.StockNumber)
            {
                return(ApiResponse.BadRequest("超过你的持股数量了"));
            }
            else
            {
                SellStock sellStock = new SellStock();
                try
                {
                    List <SimulationStock> simulationStocks = db.SimulationStocks.Where(s => s.StockAccountId == stockAccount.Id && s.Valid == true).ToList();
                    if (simulationStocks.Count > 0)
                    {
                        string[]      stockCodes     = simulationStocks.Select(s => s.StockCode).ToArray();
                        StringBuilder request_string = new StringBuilder();
                        for (int i = 0; i < stockCodes.Length; i++)
                        {
                            if (i == stockCodes.Length - 1)
                            {
                                request_string.Append(stockCodes[i]);
                            }
                            else
                            {
                                request_string.Append(stockCodes[i] + ",");
                            }
                        }
                        string res = new ShowApiRequest("http://route.showapi.com/131-46", "138438", "dd520f20268747d4bbda22ac31c9cbdf")
                                     .addTextPara("stocks", request_string.ToString())
                                     .addTextPara("needIndex", "0")
                                     .post();
                        JObject jObject = JsonConvert.DeserializeObject <JObject>(res);
                        JArray  jArray  = JArray.Parse(jObject["showapi_res_body"]["list"].ToString());
                        for (int i = 0; i < simulationStocks.Count; i++)
                        {
                            for (int j = 0; j < jArray.Count; j++)
                            {
                                if (simulationStocks[i].StockCode == jArray[j]["code"].ToString())
                                {
                                    simulationStocks[i].NowPrice        = Double.Parse(jArray[j]["nowPrice"].ToString());
                                    db.Entry(simulationStocks[i]).State = EntityState.Modified;
                                    db.SaveChanges();
                                }
                            }
                            Thread.Sleep(1);
                        }

                        sellStock.SellPrice       = simulationStock.NowPrice;
                        sellStock.SellStockNumber = SellNumber;
                        sellStock.BuyPrice        = simulationStock.BuyPrice;
                        sellStock.StockName       = simulationStock.StockName;
                        sellStock.StockCode       = simulationStock.StockCode;
                        sellStock.SellTime        = DateTime.Now;
                        sellStock.StockAccountId  = stockAccount.Id;
                        db.SellStocks.Add(sellStock);
                        if (SellNumber == simulationStock.StockNumber)
                        {
                            simulationStock.StockNumber     = 0;
                            simulationStock.Valid           = false;
                            db.Entry(simulationStock).State = EntityState.Modified;
                            db.SaveChanges();
                            Thread.Sleep(1);
                        }
                        else
                        {
                            simulationStock.StockNumber    -= SellNumber;
                            db.Entry(simulationStock).State = EntityState.Modified;
                            db.SaveChanges();
                            Thread.Sleep(1);
                        }
                        try
                        {
                            double StockValue           = 0;
                            List <SimulationStock> last = db.SimulationStocks.Where(s => s.StockAccountId == stockAccount.Id && s.Valid == true).ToList();
                            foreach (var item in last)
                            {
                                StockValue += item.NowPrice * item.StockNumber;
                            }
                            StockAccount stockAccount2 = db.StockAccounts.FirstOrDefault(s => s.UserId == UserId);
                            stockAccount2.SumStockValue   = StockValue;
                            db.Entry(stockAccount2).State = EntityState.Modified;
                            db.SaveChanges();
                            Thread.Sleep(1);
                            StockAccount stockAccount3 = db.StockAccounts.FirstOrDefault(s => s.UserId == UserId);
                            stockAccount3.Profit_or_Loss += (sellStock.SellPrice - sellStock.BuyPrice) * SellNumber;

                            stockAccount3.ValidMoney     += sellStock.SellPrice * SellNumber;
                            stockAccount3.SumMoney        = Initial_ValidMoney + sellStock.SellPrice * SellNumber;
                            db.Entry(stockAccount3).State = EntityState.Modified;
                            Thread.Sleep(1);
                            TradeHistory tradeHistory = new TradeHistory()
                            {
                                StockName         = simulationStock.StockName,
                                StockCode         = simulationStock.StockCode,
                                StockAccountId    = stockAccount.Id,
                                TransactionValue  = sellStock.SellPrice * SellNumber,
                                TransactionPrice  = sellStock.SellPrice,
                                TransactionAmount = SellNumber,
                                TransactionType   = Enums.TransactionType.卖出,
                                TradeTime         = DateTime.Now
                            };
                            db.TradeHistories.Add(tradeHistory);
                            db.SaveChanges();
                        }
                        catch (Exception ex)
                        {
                            db.Entry(simulationStock).State = EntityState.Unchanged;
                            db.Entry(stockAccount).State    = EntityState.Unchanged;
                        }
                    }
                }
                catch (Exception ex)
                {
                    return(ApiResponse.BadRequest("糟糕,网络好像出问题了"));
                }
                return(ApiResponse.Ok(new
                {
                    sellStock.SellPrice,
                    sellStock.SellStockNumber,
                    sellStock.SellTime,
                    sellStock.StockCode,
                    sellStock.StockName,
                    sellStock.BuyPrice,
                    message = "您卖出 " + sellStock.StockName + "(" + sellStock.StockCode + ") " + sellStock.SellStockNumber + "股, " + "收益为¥" + (sellStock.SellPrice - sellStock.BuyPrice) * sellStock.SellStockNumber,
                }));
            }
        }
Ejemplo n.º 29
0
 /// <summary>
 /// Retrieves completed trades from /inventoryhistory/
 /// </summary>
 /// <param name="limit">Max number of trades to retrieve</param>
 /// <returns>A List of 'TradeHistory' objects</returns>
 public List<TradeHistory> GetTradeHistory(int limit = 0)
 {
     // most recent trade is first
     List<TradeHistory> TradeHistoryList = new List<TradeHistory>();
     var url = "http://steamcommunity.com/profiles/" + BotId.ConvertToUInt64() + "/inventoryhistory/";
     var html = RetryWebRequest(SteamWeb, url, "GET", null);
     // TODO: handle rgHistoryCurrency as well
     Regex reg = new Regex("rgHistoryInventory = (.*?)};");
     Match m = reg.Match(html);
     if (m.Success)
     {
         var json = m.Groups[1].Value + "}";
         var schemaResult = JsonConvert.DeserializeObject<Dictionary<int, Dictionary<ulong, Dictionary<ulong, GenericInventory.Inventory.Item>>>>(json);
         var trades = new Regex("HistoryPageCreateItemHover\\((.*?)\\);");
         var tradeMatches = trades.Matches(html);
         foreach (Match match in tradeMatches)
         {
             if (match.Success)
             {
                 var tradeHistoryItem = new TradeHistory();
                 tradeHistoryItem.ReceivedItems = new List<Trade.TradeAsset>();
                 tradeHistoryItem.GivenItems = new List<Trade.TradeAsset>();
                 var historyString = match.Groups[1].Value.Replace("'", "").Replace(" ", "");
                 var split = historyString.Split(',');
                 var tradeString = split[0];
                 var tradeStringSplit = tradeString.Split('_');
                 var tradeNum = Convert.ToInt32(tradeStringSplit[0].Replace("trade", ""));
                 if (limit > 0 && tradeNum >= limit) break;
                 var appId = Convert.ToInt32(split[1]);
                 var contextId = Convert.ToUInt64(split[2]);
                 var itemId = Convert.ToUInt64(split[3]);
                 var amount = Convert.ToInt32(split[4]);
                 var historyItem = schemaResult[appId][contextId][itemId];
                 var genericItem = new Trade.TradeAsset(appId, contextId, itemId, amount);
                 // given item has ownerId of 0
                 // received item has ownerId of own SteamID
                 if (historyItem.OwnerId == 0)
                     tradeHistoryItem.GivenItems.Add(genericItem);
                 else
                     tradeHistoryItem.ReceivedItems.Add(genericItem);
                 TradeHistoryList.Add(tradeHistoryItem);
             }
         }
     }
     return TradeHistoryList;
 }
Ejemplo n.º 30
0
        protected void renderCandle(xGraphics g, stCell c)
        {
            int x, y;

            x = c.x;
            y = 0;

            uint color;

            object o = getUserData();
            String code;

            if (o is String)
            {
                code = (String)o;
            }
            else
            {
                stGainloss gainloss = (stGainloss)o;
                code = gainloss.code;
            }

            if (code == null)
            {
                return;
            }
            stPriceboardState ps = Context.getInstance().mPriceboard.getPriceboard(code);

            if (ps == null)
            {
                return;
            }

            Context ctx = Context.getInstance();

            float price = ps.getCurrentPrice();
            float open  = ctx.mPriceboard.getOpen(ps.getID());

            if (open == 0)
            {
                open = price;
            }

            float hi = ps.getMax();
            float lo = ps.getMin();

            //  check hi/lo valid

            if ((hi == 0 || lo == 0))
            {
                TradeHistory trade = Context.getInstance().getTradeHistory(ps.getID());
                float[]      hl    = new float[2];
                if (trade != null && trade.getHiLo(hl))
                {
                    if (hi == 0)
                    {
                        hi = hl[0];
                    }
                    if (lo == 0)
                    {
                        lo = hl[1];
                    }
                }
            }

            if (hi == lo)
            {
                hi = price;
            }

            if (hi == 0)
            {
                hi = open > price ? open : price;
            }
            if (lo == 0)
            {
                lo = open < price ? open : price;
            }
            if (lo == 0)
            {
                lo = hi;
            }
            //---------------------------------------------

            float priceLen = (float)(hi - lo);

            int y0 = 0;

            float min = ps.getRef() - (ps.getRef() / 13);       //	+-7% (7*13==100)
            float max = ps.getRef() + (ps.getRef() / 13);

            if (ps.getMarketID() == 1)
            {
                min = ps.getRef() - (ps.getRef() / 19); //	+-5%
                max = ps.getRef() + (ps.getRef() / 19);
            }

            if (min > lo && lo > 0)
            {
                min = (float)lo;
            }
            if (max < hi)
            {
                max = (float)hi;
            }

            float totalPrice = (max - min);  //(10%);

            if (totalPrice < priceLen)
            {
                totalPrice = priceLen;
            }

            if (totalPrice == 0)
            {
                return;
            }

            float ry = (float)(getH() - 2 * y0) / totalPrice;

            int totalH = (int)(ry * totalPrice);
            int bodyW  = c.w / 2;

            //================frame=============================
            //  line _ref
            g.setColor(0x70ffff00);
            y = (int)(y0 + totalH - (ps.getRef() - min) * ry);
            g.drawLineDotHorizontal(c.x + 1, y, c.w - 2);
            //===================================================
            if (price == 0)
            {
                return; //	khong co giao dich
            }
            color = price < open ? C.COLOR_RED : C.COLOR_GREEN;
            if (price == open)
            {
                color = C.COLOR_WHITE;
            }

            //  draw shadow
            g.setColor(C.COLOR_WHITE);
            x = c.x + c.w / 2;

            if (lo > 0 && hi > 0)
            {
                int minY = (int)(y0 + totalH - (lo - min) * ry);
                int maxY = (int)(y0 + totalH - (hi - min) * ry);

                g.drawLine(x, maxY, x, minY);
            }
            int centerX = x + bodyW / 2;
            //  candle's body
            int oY = (int)(y0 + totalH - (open - min) * ry);
            int cY = (int)(y0 + totalH - (price - min) * ry);

            y = oY < cY ? oY : cY;
            int bodyH = Utils.ABS_INT(cY - oY);

            if (bodyH < 2)
            {
                bodyH = 2;
            }
            g.setColor(color);
            g.fillRect(x - bodyW / 2, y, bodyW, bodyH);
        }
Ejemplo n.º 31
0
        private IQueryable <TradeHistory> GenerateTradeHistories()
        {
            int    count     = 0;
            Random random    = new Random();
            var    histories = new List <TradeHistory>();

            var totalFeesByCurrency = new Dictionary <int, decimal>();

            while (count < 10000)
            {
                Guid uId   = _users.ElementAt(random.Next(1, _users.Count())).Id;
                Guid toUId = _users.ElementAt(random.Next(1, _users.Count())).Id;

                while (toUId == uId)
                {
                    toUId = _users.ElementAt(random.Next(1, _users.Count())).Id;
                }

                decimal amount = random.Next(1, 1000000);
                decimal rate   = (decimal)0.00000005;
                decimal fee    = (amount * rate) * (decimal)0.2;

                var currencyId = 0;
                var rand       = random.Next(1, 1000);
                if (rand > 250)
                {
                    currencyId = random.Next(990, 999);
                }
                else
                {
                    currencyId = random.Next(1, 7);
                }

                var pairs = _tradePairs.Where(x => x.CurrencyId1 == currencyId).ToList();

                if (!pairs.Any())
                {
                    while (!pairs.Any())
                    {
                        currencyId = random.Next(1, 1000) > 250 ? random.Next(990, 999) : random.Next(1, 7);
                        pairs      = _tradePairs.Where(x => x.CurrencyId1 == currencyId).ToList();
                    }
                }

                var tradePair = pairs[random.Next(0, pairs.Count - 1)];

                TradeHistory th = new TradeHistory
                {
                    UserId      = uId,
                    ToUserId    = toUId,
                    CurrencyId  = currencyId,
                    TradePairId = tradePair.Id,
                    Amount      = amount,
                    Rate        = rate,
                    Fee         = fee,
                    Timestamp   = _testMonth
                };

                histories.Add(th);

                if (totalFeesByCurrency.ContainsKey(tradePair.CurrencyId2))
                {
                    decimal current = totalFeesByCurrency[tradePair.CurrencyId2];
                    totalFeesByCurrency[tradePair.CurrencyId2] = (current + fee);
                }
                else
                {
                    totalFeesByCurrency[tradePair.CurrencyId2] = fee;
                }

                count++;
            }

            foreach (var kvp in totalFeesByCurrency)
            {
                // multiply by two for both sides of the transaction
                var total = (kvp.Value * 2);
                _expectedFeeTotalsByCurrency[kvp.Key] = total;
                _expectedPortionOfCurrency[kvp.Key]   = ((total * FOUR_POINT_FIVE_PERCENT) / TOTAL_PORTIONS);
            }

            return(histories.AsQueryable());
        }