private async Task DoTimer(ITimerTrigger timer, TimerTriggeredHandlerArgs args, CancellationToken ct)
        {
            if (!StartWork())
            {
                return;
            }

            try
            {
                using (var context = CreateContext())
                {
                    var tradeRequest = new TradesHistoryRequest {
                        Limit = 10
                    };
                    var data = await _b2C2RestClient.GetTradeHistoryAsync(tradeRequest, ct);

                    var added = 0;
                    do
                    {
                        added = 0;
                        foreach (var log in data.Data)
                        {
                            foreach (var assetMapping in _assetMappings)
                            {
                                log.AssetPair = log.AssetPair.Replace(assetMapping.Key, assetMapping.Value);
                            }

                            var item = await context.Trades.FirstOrDefaultAsync(e => e.TradeId == log.TradeId, ct);

                            if (item != null)
                            {
                                continue;
                            }

                            item = new TradeEntity(log);
                            context.Trades.Add(item);
                            added++;
                        }

                        await context.SaveChangesAsync(ct);

                        tradeRequest.Cursor = data.Next;
                        data = await _b2C2RestClient.GetTradeHistoryAsync(tradeRequest, ct);
                    } while (added > 0);
                }
            }
            finally
            {
                StopWork();
            }
        }
        private AccountEntity toAccountEntity(Document doc, bool includeTrades = false)
        {
            AccountEntity en = null;

            if (doc != null)
            {
                en      = new AccountEntity();
                en.Id   = doc["id"].ToString();
                en.Name = doc.ContainsKey("name") ? doc["name"].ToString() : "";

                if (includeTrades)
                {
                    en.Trades = new List <TradeEntity>();

                    if (doc.ContainsKey("trades"))
                    {
                        var tradesDoc = doc["trades"] as DynamoDBList;

                        foreach (var item in tradesDoc.Entries)
                        {
                            Document    tradeDoc = item as Document;
                            TradeEntity trade    = new TradeEntity();

                            trade.Id         = tradeDoc["id"].AsString();
                            trade.Code       = tradeDoc["code"].AsString();
                            trade.Direction  = tradeDoc["direction"].AsInt();
                            trade.EntryDate  = tradeDoc["entryDate"].AsInt();
                            trade.EntryPrice = tradeDoc["entryPrice"].AsDouble();

                            if (tradeDoc.ContainsKey("exitDate"))
                            {
                                trade.ExitDate = tradeDoc["exitDate"].AsInt();
                            }

                            if (tradeDoc.ContainsKey("exitPrice"))
                            {
                                trade.ExitPrice = tradeDoc["exitPrice"].AsDouble();
                            }

                            if (tradeDoc.ContainsKey("pl"))
                            {
                                trade.PL = tradeDoc["pl"].AsDouble();
                            }
                            en.Trades.Add(trade);
                        }
                    }
                }
            }
            return(en);
        }
        private Document toTradeDocument(TradeEntity trade)
        {
            Document doc = new Document();

            doc["id"]         = trade.Id;
            doc["code"]       = trade.Code;
            doc["direction"]  = trade.Direction;
            doc["entryDate"]  = trade.EntryDate;
            doc["entryPrice"] = trade.EntryPrice;
            doc["exitDate"]   = trade.ExitDate;
            doc["exitPrice"]  = trade.ExitPrice;
            doc["pl"]         = trade.PL;

            return(doc);
        }
Exemplo n.º 4
0
        public static void TradeTree_RecursiveAdd(Trade trade, TradeEntity t)
        {
            if (trade == null)
            {
                return;
            }

            if (trade.level == t.ts_id.Length - 2)    // 目标节点 t 的 候选 parents 所在的 trade
            {
                trade.trades.FirstOrDefault(tr => t.ts_id.StartsWith(tr.code))?.trades?.Add(new Trade(t.ts_id, t.ts_name));
            }
            else
            {
                TradeTree_RecursiveAdd(trade.trades.FirstOrDefault(tr => t.ts_id.StartsWith(tr.code)), t);
            }
        }
        private async Task DoTimer(ITimerTrigger timer, TimerTriggeredHandlerArgs args, CancellationToken ct)
        {
            if (!StartWork())
            {
                return;
            }

            var offset = 0;
            var page   = 100;

            try
            {
                using (var context = CreateContext())
                {
                    // Update trades from last time
                    var data = await _b2C2RestClient.GetTradeHistoryAsync(offset, page, ct);

                    var added = 0;
                    do
                    {
                        added = 0;
                        foreach (var log in data)
                        {
                            var item = await context.Trades.FirstOrDefaultAsync(e => e.TradeId == log.TradeId, ct);

                            if (item != null)
                            {
                                continue;
                            }

                            item = new TradeEntity(log);
                            context.Trades.Add(item);
                            added++;
                        }

                        await context.SaveChangesAsync(ct);

                        offset += data.Count;
                        data    = await _b2C2RestClient.GetTradeHistoryAsync(offset, page, ct);
                    } while (added > 0);
                }
            }
            finally
            {
                StopWork();
            }
        }
        static TradeEntity Parse(string str)
        {
            var result = new TradeEntity();

            var fields = str.Split(',');

            result.TradeId           = fields[0];
            result.User              = fields[1];
            result.Price             = decimal.Parse(fields[2], CultureInfo.InvariantCulture);
            result.Volume            = decimal.Parse(fields[3], CultureInfo.InvariantCulture);
            result.Direction         = fields[4];
            result.AssetPair         = fields[5];
            result.RequestForQuoteId = "";
            result.Created           = DateTime.Parse(fields[8], CultureInfo.InvariantCulture);

            return(result);
        }
        private async Task DoAdd(SqlConnection conn, SqlTransaction transaction, IOrderHistory order, ITrade trade)
        {
            var orderHistoryEntity = OrderHistoryEntity.Create(order);
            await conn.ExecuteAsync(
                $"insert into {TableName} ({GetColumns}) values ({GetFields})",
                orderHistoryEntity,
                transaction);

            if (trade != null)
            {
                var tradeEntity = TradeEntity.Create(trade);
                await conn.ExecuteAsync(
                    $"insert into {TradesSqlRepository.TableName} ({TradesSqlRepository.GetColumns}) values ({TradesSqlRepository.GetFields})",
                    tradeEntity,
                    transaction);
            }
        }
Exemplo n.º 8
0
        public async Task OpenPosition(string accountId, string tradeId, string code, int direction, double entryPrice, int entryDate)
        {
            AccountEntity account = await this.dal.GetItem(accountId);

            if (account.Trades == null)
            {
                account.Trades = new List <TradeEntity>();
            }

            TradeEntity trade = new TradeEntity
            {
                Id         = tradeId,
                Code       = code,
                Direction  = direction,
                EntryDate  = entryDate,
                EntryPrice = entryPrice
            };

            account.Trades.Add(trade);

            await this.dal.Update(account);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Trade
        /// </summary>
        /// <param name="symbolId">Symbol id</param>
        /// <param name="side">buy or sell</param>
        /// <param name="price">Base Price</param>
        /// <param name="amount">Amount</param>
        /// <param name="retryCount">Retry count when failed</param>
        /// <returns>Trade entity</returns>
        private TradeEntity Trade(int symbolId, TradeTypes side, decimal price, decimal amount, int retryCount = 1)
        {
            if (retryCount > ConfigTool.TradeFailedRetryCount)
            {
                // If retry ended, return
                return(null);
            }
            TradeEntity te          = new TradeEntity();
            bool        isSucceeded = false;

            try
            {
                if (ConfigTool.RunMode == RunMode.TEST)
                {
                    if (side == TradeTypes.BUY && TestConfigTool.TradeBaseToCoinFailed)
                    {
                        return(null);
                    }
                    else if (side == TradeTypes.SELL && TestConfigTool.TradeCoinToBaseFailed)
                    {
                        return(null);
                    }
                    else
                    {
                        // If test
                        var receivedValue = amount.ToString();
                        var remainsValue  = amount.ToString();
                        var orderId       = "1";
                        var receivedD     = (decimal)double.Parse(receivedValue);
                        var remainsD      = (decimal)double.Parse(remainsValue);
                        te.Received = receivedD;
                        te.Remains  = remainsD;
                        te.OrderId  = orderId;
                        isSucceeded = true;
                    }
                }
                else
                {
                    XElement data = null;

                    if (side == TradeTypes.BUY)
                    {
                        //Try to buy
                        data = privateApiInstance.BuyOrder(symbolId, price.ToString(), amount.ToString());
                    }
                    else
                    {
                        //Try to sell
                        data = privateApiInstance.SellOrder(symbolId, price.ToString(), amount.ToString());
                    }

                    var id = data.Element("data").Element("order_id");
                    if (id != null && !string.IsNullOrEmpty(id.Value))
                    {
                        // If id is returned
                        var receivedValue = data.Element("data").Element("trade_volume").Value;
                        var remainsValue  = data.Element("data").Element("volume").Value;
                        var orderId       = id.Value;
                        var receivedD     = (decimal)double.Parse(receivedValue);
                        var remainsD      = (decimal)double.Parse(remainsValue);
                        te.Received = receivedD;
                        te.Remains  = remainsD;
                        te.OrderId  = orderId;
                        isSucceeded = true;
                    }
                    else
                    {
                        // If result is incorrect, output error log and retry if retry count is set
                        var logMsg = "Error happened when trading in dragonex.The result is:" + data.ToString();
                        LogTool.LogTradeInfo(logMsg, LogLevels.ERROR);
                        return(Trade(symbolId, side, price, amount, ++retryCount));
                    }
                }
            }
            catch (Exception ex)
            {
                // If any error happened when Trading, out error log
                var logMsg = "Exception happened when trading in dragonex.Exception:" + Environment.NewLine
                             + ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine;
                LogTool.LogTradeInfo(logMsg, LogLevels.ERROR);
                return(Trade(symbolId, side, price, amount, ++retryCount));
            }
            te.Success = isSucceeded;
            return(te);
        }