Example #1
0
        private void SelectedGameScreen_SelectGame(string message)
        {
            switch (message)
            {
            case "Set Indian Poker Screen":
                this.SetVisible(Screen.IndianPoker);

                MatchingData matchingData = new MatchingData();
                matchingData.GameID      = (byte)KindOfGame.IndianPokser;
                matchingData.matchingMsg = (byte)Matching.StartMatching;
                matchingData.Ack         = 1;
                indianPokserClient.SendMessage(Header.Matching, matchingData);

                //if(indianPokserClient.RequestMatch()) // 서버에 매치요청 보냄
                //{

                //}
                break;

            case "Set Maze of Memory Screen":
                this.SetVisible(Screen.MazeofMemory);
                break;

            default:
                break;
            }
        }
Example #2
0
        public double GetProfitRatio(IExchange ex1, IExchange ex2, Instrument ins, MatchingData data)
        {
            data.AskPrice1 = ins.GetAskPrice(ex1);
            data.BidPrice2 = ins.GetBidPrice(ex2);
            SetUsdAmounts(ex1, ex2, data);

            return(data.ProfitRatio);
        }
Example #3
0
 private void SetUsdAmounts(IExchange ex1, IExchange ex2, MatchingData data)
 {
     data.BuyUsdAmount  = data.AskPrice1 * data.Amount;
     data.SellUsdAmount = data.BidPrice2 * data.Amount;
     data.Profit        = Math.Round(data.SellUsdAmount - data.BuyUsdAmount, ex1.CountryCurrencyDecimal);
     data.Fees          = (data.BuyUsdAmount * ex1.TradingFee) + (data.SellUsdAmount * ex2.TradingFee);
     data.Profit        = Math.Round(data.Profit - data.Fees, ex1.CountryCurrencyDecimal);
     data.ProfitRatio   = Math.Round(data.Profit / data.SellUsdAmount * 100, ex1.CountryCurrencyDecimal);
 }
Example #4
0
        public bool Serialize(MatchingData packet)
        {
            bool ret = true;

            int request = (int)packet.request;

            ret &= Serialize(request);
            return(ret);
        }
Example #5
0
        public void ExecuteOrdersAsync(IExchange ex1, IExchange ex2, MatchingData data)
        {
            string        order1 = null;
            string        order2 = null;
            Task <string> task1  = null;
            Task <string> task2  = null;

            if (FastExchanges.ContainsKey(ex1.GetExchangeName()))
            {
                task1 = Task <string> .Run(() => PlaceOrder(ex1, data.AskPrice1, data.Amount, OrderSide.BID, data));

                order1 = task1.Result;
            }
            else
            {
                order1 = PlaceOrder(ex1, data.AskPrice1, data.Amount, OrderSide.BID, data);
            }

            if (FastExchanges.ContainsKey(ex2.GetExchangeName()))
            {
                task2 = Task <string> .Run(() => PlaceOrder(ex2, data.BidPrice2, data.Amount, OrderSide.ASK, data));

                order2 = task2.Result;
            }
            else
            {
                order2 = PlaceOrder(ex2, data.BidPrice2, data.Amount, OrderSide.ASK, data);
            }

            if (order1 == null && order2 == null)
            {
                data.TransactionState = TradingState.Fail12;
                return;
            }

            if (order1 == null)
            {
                data.TransactionState = TradingState.Fail1;
            }
            else
            {
                data.Order1 = order1;
            }

            if (order2 == null)
            {
                data.TransactionState = TradingState.Fail2;
            }
            else
            {
                data.Order2 = order2;
            }

            ex1.RemoveOrders();
            ex2.RemoveOrders();
        }
Example #6
0
    //매칭 요청
    public void SendLocalMatchingRequest()
    {
        MatchingData matchingData = new MatchingData();

        matchingData.request = MatchingPacketId.MatchingRequest;
        Debug.Log("매칭 데이터 : " + matchingData);
        MatchingPacket packet = new MatchingPacket(matchingData);

        networkManager.SendReliable <MatchingData>(packet);
    }
Example #7
0
        private void InitPrices(MatchingData data, double bidPrice, double askPrice, double bidOrderAmount, double askOrderAmount)
        {
            data.AskPrice1 = askPrice;
            Utils.ThrowIf(data.AskPrice1 == 0, "AskPrice1 == 0");

            data.BidPrice2 = bidPrice;
            Utils.ThrowIf(data.BidPrice2 == 0, "BidPrice2 == 0");

            data.AskAmount = askOrderAmount;
            data.BidAmount = bidOrderAmount;
        }
        //Match button clicked
        private void matchButton_Click(object sender, EventArgs e)
        {
            EEG_Logger p = new EEG_Logger(); //Creating a new object of the class and acting upon it

            for (int i = 0; i < 10; i++)
            {
                pBar.PerformStep();
                p.Run();
                Thread.Sleep(1660); //Slow down the process, so the user can see what's happening and also to pull data for a specified amount of time
                //1660 for 15.03 Seconds
            }

            Centroid temp_centroid = new Centroid("temp", 0);

            temp_centroid = read_CSV().read_matching_records(); //Reading the .csv file

            File.Delete("outfile.csv");
            pBar.Value = 0;
            MessageBox.Show("Matching complete.");

            MatchingData m = new MatchingData();

            this.label4.Text    = m.match_data(collection, temp_centroid);
            this.label4.Visible = true;
            Thread.Sleep(1500);
            //This is to calculate our error rate to make see how accurate we are at predicting the right word
            DialogResult answer = MessageBox.Show("Did we match the right word?", "Speak Your Mind", MessageBoxButtons.YesNo);

            if (answer == DialogResult.Yes)
            {
                int yesCount;
                yesCount = Convert.ToInt32(this.userInfoStringParsed[16]) + 1;
                this.userInfoStringParsed[16] = yesCount.ToString();
                this.userInfoString           = "";
                foreach (string s in this.userInfoStringParsed)
                {
                    this.userInfoString += (s + ",");
                }
                this.userInfoString = this.userInfoString.Substring(0, this.userInfoString.Length - 1);
            }
            else if (answer == DialogResult.No)
            {
                int noCount;
                noCount = Convert.ToInt32(this.userInfoStringParsed[17]) + 1;
                this.userInfoStringParsed[17] = noCount.ToString();
                this.userInfoString           = "";
                foreach (string s in this.userInfoStringParsed)
                {
                    this.userInfoString += (s + ",");
                }
                this.userInfoString = this.userInfoString.Substring(0, this.userInfoString.Length - 1);
            }
        }
Example #9
0
        private DynamicParameters SaveAccountProcParams2(MatchingData data, int tradeId, double balance)
        {
            var args = new DynamicParameters();

            args.Add("@tradeId", tradeId);
            args.Add("@exchange2", (int)data.Exchange2);
            args.Add("@currencyRate2", data.CurrencyRate2);
            args.Add("@amount", data.Amount);
            args.Add("@balance", balance);

            return(args);
        }
Example #10
0
        //메시지 전달
        private bool SendMessage2(short id, int value)
        {
            MatchingData message = new MatchingData();

            message.GameID      = (byte)KindOfGame.IndianPokser;
            message.Ack         = 1;
            message.matchingMsg = (byte)Matching.StartMatching;

            //byte[] sendMessage = packetDefine.MakePacket(message);
            //stream.Write(sendMessage, 0, sendMessage.Length);
            return(true);
        }
Example #11
0
        private MatchingData InitTransData(double amount, Instrument instrument)
        {
            var data = new MatchingData {
                CreatedAt = DateTime.UtcNow
            };

            data.TransactionState = TradingState.Reject;
            data.Instrument       = instrument.GetInstrument();
            data.Amount           = amount;

            return(data);
        }
Example #12
0
    private List <MatchingData> getData()
    {
        //Remove all data without chosen topics
        string[] chosenTopics = GameObject.FindGameObjectWithTag("GameLogic").GetComponent <GameStats>().getChosenTopics();

        //Get the real fake data from data object
        List <MatchingData> dataList = GameObject.FindGameObjectWithTag("GameLogic").GetComponent <GamesData>().getMatchingData();

        List <MatchingData> shuffledData = dataList.OrderBy(x => UnityEngine.Random.value).ToList();
        MatchingData        d            = shuffledData[0];

        data = d;
        shuffledData.Remove(d);
        return(shuffledData);
    }
Example #13
0
        public bool Deserialize(ref MatchingData element)
        {
            // 데이터가 정의되어있지 않다면
            if (GetDataSize() == 0)
            {
                return(false);
            }

            bool ret = true;

            int request = 0;

            ret            &= Deserialize(ref request);
            element.request = (MatchingPacketId)request;

            return(ret);
        }
Example #14
0
        /// <summary>
        /// Adds a sub-event (child) to this event if it doesn't exist, or increase the duration by the
        /// duration of the provided event.
        /// </summary>
        /// <param name="ChildData">The sub-event to add to this event.</param>
        public void AddChild(TimingData ChildData)
        {
            TimingData MatchingData;

            if (Children.TryGetValue(ChildData.Name, out MatchingData))
            {
                MatchingData.ExclusiveDuration += ChildData.ExclusiveDuration;
                foreach (TimingData ChildChildData in ChildData.Children.Values)
                {
                    MatchingData.AddChild(ChildChildData);
                }
            }
            else
            {
                Children.Add(ChildData.Name, ChildData);
            }
        }
Example #15
0
        private DynamicParameters SaveAccountProcParams(MatchingData data, int tradeId)
        {
            var args = new DynamicParameters();

            args.Add("@tradeId", tradeId);
            args.Add("@exchange1", (int)data.Exchange1);
            args.Add("@exchange2", (int)data.Exchange2);
            args.Add("@currencyRate1", data.CurrencyRate1);
            args.Add("@currencyRate2", data.CurrencyRate2);
            args.Add("@amount", data.Amount);
            args.Add("@buyUsdAmount", data.BuyUsdAmount);
            args.Add("@sellUsdAmount", data.SellUsdAmount);
            args.Add("@transCode", data.TransactionState.ToString());
            args.Add("@currencyCode", data.Instrument.ToString());

            return(args);
        }
Example #16
0
        public TradingState Trading(IExchange ex1, IExchange ex2, Instrument ins, MatchingData data, double maxBid, double minAsk, int depth = 0)
        {
            data.SetExchange1(ex1);
            data.SetExchange2(ex2);

            InitPrices(data, maxBid, minAsk, ins.GetBidOrderAmount(ex2), ins.GetAskOrderAmount(ex1));
            SetUsdAmounts(ex1, ex2, data);

            if (data.ProfitRatio < 0)
            {
                return(depth == 1 ? TradingState.Negative : Trading(ex2, ex1, ins, data, maxBid, minAsk, 1));
            }

            var state = CheckBalancesImpl(ex1, ex2, ins, data);

            if (state != TradingState.Ok)
            {
                return(state);
            }

            state = _profitStrategy.GetProfitState(data, ins.GetProfitRatios(), multiplier =>
            {
                if (multiplier != 1)
                {
                    SetUsdAmounts(ex1, ex2, data);
                }
                return(CheckBalancesImpl(ex1, ex2, ins, data));
            });

            if (state != TradingState.Ok)
            {
                return(state);
            }

            if (data.Profit < ins.GetMinUsdProfit())
            {
                return(TradingState.NoProfit);
            }

            return(TradingState.Ok);
        }
Example #17
0
        private DynamicParameters SaveTradeProcParams(MatchingData data)
        {
            var args = new DynamicParameters();

            args.Add("@createdAt", data.CreatedAt);
            args.Add("@exchange1", (int)data.Exchange1);
            args.Add("@exchange2", (int)data.Exchange2);
            args.Add("@order1", data.Order1);
            args.Add("@order2", data.Order2);
            args.Add("@profitRatio", data.ProfitRatio);
            args.Add("@currentProfitRatio", data.CurrentProfitRatio);
            args.Add("@profit", data.Profit);
            args.Add("@amount", data.Amount);
            args.Add("@askAmount", data.AskAmount);
            args.Add("@bidAmount", data.BidAmount);
            args.Add("@askPrice1", data.AskPrice1);
            args.Add("@bidPrice2", data.BidPrice2);
            args.Add("@instrumentId", (int)data.Instrument);
            args.Add("@transCode", data.TransactionState.ToString());

            return(args);
        }
Example #18
0
        public TradingState GetProfitState(MatchingData data, List <Tuple <double, double> > profitRatios, Func <double, TradingState> checkBalances)
        {
            if (data.ProfitRatio < profitRatios.Last().Item1)
            {
                return(TradingState.NoProfit);
            }

            double buyAmount         = Math.Min(data.AskAmount, data.BidAmount);
            double balanceMultiplier = 1;

            foreach (var ratio in profitRatios)
            {
                if (data.ProfitRatio >= ratio.Item1)
                {
                    balanceMultiplier = ratio.Item2;
                    break;
                }
            }
            data.Amount = Math.Min(buyAmount, data.Amount * balanceMultiplier);

            return(checkBalances(balanceMultiplier));
        }
        //메시지 전달
        private bool SendMessage(short id, int value)
        {
            MatchingData message = new MatchingData();

            message.MessageID   = (byte)MessageID.IndianPokser;
            message.Ack         = 1;
            message.matchingMsg = (byte)Matching.StartMatching;

            byte[] sendMessage = packetDefine.MakePacket(message);
            stream.Write(sendMessage, 0, sendMessage.Length);
            return(true);

            //a
            //a
            //string msg = "matching";
            //byte[] header = BitConverter.GetBytes(id);
            //byte[] body = BitConverter.GetBytes(value);
            //int length = header.Length + body.Length;
            //byte[] leng = BitConverter.GetBytes(length);
            //byte[] packet = new byte[length+sizeof(int)];

            //Array.Copy(header, 0, packet, 0, header.Length);
            //Array.Copy(leng, 0, packet, header.Length, leng.Length);
            //Array.Copy(body, 0, packet, header.Length + leng.Length, body.Length);

            //try
            //{
            //    stream.Write(packet, 0, packet.Length);
            //    stream.Flush();
            //    return true;
            //}
            //catch
            //{
            //    Console.WriteLine("메시지 전송 실패");
            //    return false;
            //}
        }
Example #20
0
        private string PlaceOrder(IExchange ex, double price, double amount, OrderSide side, MatchingData data)
        {
            OrderResponse order = null;

            try
            {
                order = ex.PlaceOrder(Math.Round(price, ex.CountryCurrencyDecimal),
                                      Math.Round(amount, ex.CryptoCurrencyDecimal),
                                      data.Instrument,
                                      side);
            }
            catch (Exception e)
            {
                if (side == OrderSide.BID)
                {
                    data.FailReason1 = e.Message;
                }
                else
                {
                    data.FailReason2 = e.Message;
                }
                return(null);
            }
            if (order.Success)
            {
                if (side == OrderSide.BID)
                {
                    data.FailReason1 = order.ErrorReason;
                }
                else
                {
                    data.FailReason2 = order.ErrorReason;
                }
                return(null);
            }

            if (side == OrderSide.BID)
            {
                data.BuyUsdAmount = (1 - ex.TradingFee) * data.BuyUsdAmount;
            }
            else
            {
                data.SellUsdAmount = (1 - ex.TradingFee) * data.SellUsdAmount;
            }

            return(order.OrderId);
        }
Example #21
0
        public void SaveTransaction(MatchingData data, Action <Exception> onException)
        {
            using (var db = DbConnection)
            {
                var count = db.Query <int>(DbQueryStr.TradeExist, data).Single();
                if (count > 0)
                {
                    return;
                }

                db.Open();

                var args      = SaveTradeProcParams(data);
                var trans     = db.BeginTransaction();
                int tradeId   = 0;
                int accountId = 0;

                try
                {
#if true
                    var sql = @"
                    insert into dbo.Trade (
                        CreatedAt, ExchangeId1, ExchangeId2, OrderId1, OrderId2, ProfitRatio, Profit,
		                CurrentProfitRatio, AskAmount, BidAmount, Amount, BidPrice2, AskPrice1, CurrencyId, TransCode
	                )
	                values (
		                @createdAt, @exchange1, @exchange2, @order1, @order2, @profitRatio, @profit, @currentProfitRatio, 
		                @askAmount, @bidAmount, @amount, @bidPrice2, @askPrice1, @instrumentId, @transCode
	                );
                    select cast(scope_identity() as int)";

                    tradeId = db.Query <int>(sql, args, transaction: trans).Single();

                    if (data.TransactionState == TransactionState.Fail2 || data.TransactionState == TransactionState.OK)
                    {
                        var cryptoAmount = data.Amount;
                        var amount       = -(data.BuyUsdAmount * data.CurrencyRate1);

                        sql = @"select top 1 Id, Balance from dbo.Account where ExchangeId = @ExchangeId order by Id desc";
                        var account = db.Query <Account>(sql, new { ExchangeId = data.Exchange1 }, transaction: trans).Single();
                        var balance = Math.Round(account.Balance + amount, 2);
                        if (balance < 0)
                        {
                        }
                        sql       = @"insert into dbo.Account (ExchangeId, OperationCode, TradeId, CurrencyRate, Amount, Balance) 
		                        values (@exchange1, 'BUY', @tradeId, @currencyRate1, @amount, @balance);
                                select cast(scope_identity() as int)";
                        accountId = db.Query <int>(sql, SaveAccountProcParams1(data, tradeId, balance), transaction: trans).Single();

                        if (data.Instrument == CurrencyName.BTC)
                        {
                            InsertInstrument(db, trans, accountId, cryptoAmount, account.Id, "Btc");
                        }
                        else
                        {
                            throw new NotImplementedException();
                        }
                    }
                    if (data.TransactionState == TransactionState.Fail1 || data.TransactionState == TransactionState.OK)
                    {
                        var cryptoAmount = -data.Amount;
                        var amount       = data.SellUsdAmount * data.CurrencyRate2;

                        sql = @"select top 1 Id, Balance from dbo.Account where ExchangeId = @ExchangeId order by Id desc";
                        var account = db.Query <Account>(sql, new { ExchangeId = data.Exchange2 }, transaction: trans).Single();
                        var balance = Math.Round(account.Balance + amount, 2);

                        sql       = @"insert into dbo.Account (ExchangeId, OperationCode, TradeId, CurrencyRate, Amount, Balance) 
		                        values (@exchange2, 'SEL', @tradeId, @currencyRate2, @amount, @balance);
                                select cast(scope_identity() as int)";
                        accountId = db.Query <int>(sql, SaveAccountProcParams2(data, tradeId, balance), transaction: trans).Single();

                        if (data.Instrument == CurrencyName.BTC)
                        {
                            InsertInstrument(db, trans, accountId, cryptoAmount, account.Id, "Btc");
                        }
                        else
                        {
                            throw new NotImplementedException();
                        }
                    }
#else
                    db.Execute("SaveTrade", args, commandType: CommandType.StoredProcedure, transaction: trans);
                    tradeId = args.Get <int>("@tradeId");

                    args = SaveAccountProcParams(data, tradeId);
                    db.Execute("SaveAccount", args, commandType: CommandType.StoredProcedure, transaction: trans);
#endif
                    if (!String.IsNullOrEmpty(data.FailReason))
                    {
                        db.Execute(DbQueryStr.SaveFailReason, data, transaction: trans);
                    }
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    onException(ex);
                }
            }
        }
Example #22
0
        private List <CseProductInfo> GetProductsFromCseAction(int minNumberOfOffers)
        {
            var timer = new TimerProvider(_context, "get-campaign-apis-sql");
            var apis  = GetCseApisAndCurrencyForCurrentCampaignId();

            timer.StopTimer();

            if (apis.Count == 0)
            {
                return(new List <CseProductInfo>());
            }

            var cseDataProvider = new CseToMongoEtlProvider();

            var productsList    = new List <CseProductInfo>();
            var rawProductsList = new List <CseProductInfo>();
            var merchantsList   = new List <CseMerchantInfo>();

            int totalNumberOfOffers = 0;

            while (true)
            {
                for (int i = 0; i < apis.Count; i++)
                {
                    MatchingData matchingData = null;

                    try
                    {
                        matchingData = GetProtuctsFromCseByKeyword(apis[i]);

                        if (matchingData == null)
                        {
                            matchingData = new MatchingData();
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.ErrorFormat("failed get data from cse [{0}], ex: [{1}]", apis[i], ex.Message);
                        _context.AddCseExecutionFailure(apis[i].ToString(), "Failed");
                    }

                    _context.AddCseNumberOfRawResults(apis[i].ToString(), matchingData.Matches.Count.ToString());

                    if (matchingData.Matches.Count == 0)
                    {
                        continue;
                    }

                    _context.AddCseExecutionFailure(apis[i].ToString(), "OK");

                    List <CseProductInfo>  products  = null;
                    List <CseMerchantInfo> merchants = null;

                    cseDataProvider.ParseProductAndMerchants(apis[i], "widget", matchingData.ds, out products, out merchants);

                    if (products.Count == 0)
                    {
                        continue;
                    }

                    merchantsList.AddRange(merchants.Select(x => (CseMerchantInfo)x.Clone()));
                    rawProductsList.AddRange(products.Select(x => (CseProductInfo)x.Clone()));

                    var filterProvider = new FilterProvider(_context);

                    products = filterProvider.FilterSameStore(products);
                    products = filterProvider.FilterPriceRange(products);

                    if (products.Count == 0)
                    {
                        continue;
                    }

                    productsList.AddRange(products);

                    productsList = filterProvider.FilterDuplicateStores(productsList);
                    productsList = filterProvider.FilterDuplicateProductId(productsList);

                    if (productsList.Count == 0)
                    {
                        continue;
                    }

                    totalNumberOfOffers = CountProdcutOffers(productsList);

                    if (totalNumberOfOffers >= minNumberOfOffers)
                    {
                        break;
                    }
                }

                totalNumberOfOffers = CountProdcutOffers(productsList);

                if (totalNumberOfOffers >= minNumberOfOffers)
                {
                    break;
                }

                if (!_context.IsDefaultPrice)
                {
                    var filterProvider = new FilterProvider(_context);

                    rawProductsList = filterProvider.FilterDuplicateStores(rawProductsList);
                    rawProductsList = filterProvider.FilterDuplicateProductId(rawProductsList);

                    totalNumberOfOffers = CountProdcutOffers(rawProductsList);

                    if (totalNumberOfOffers >= minNumberOfOffers)
                    {
                        productsList = rawProductsList;
                        break;
                    }
                }

                if (!ShrinkKeywordStart())
                {
                    break;
                }
            }

            ThreadPool.QueueUserWorkItem(state =>
            {
                dynamic param = state as dynamic;

                cseDataProvider.AddCseResultToMongoDb("widget", _context.Op, param.products, param.merchants, false);
            }, new
            {
                products  = new List <CseProductInfo>(rawProductsList.Select(x => (CseProductInfo)x.Clone())),
                merchants = new List <CseMerchantInfo>(merchantsList.Select(x => (CseMerchantInfo)x.Clone()))
            });

            return(productsList);
        }
Example #23
0
        private TradingState CheckBalancesImpl(IExchange ex1, IExchange ex2, Instrument ins, MatchingData data)
        {
            double amount = data.Amount;

            #region BUY
            double              minValue     = data.AskPrice1 * ((BaseExchange)ex1).MinUsdValueRatio;
            Func <double>       reduceAmount = () => (ex1.UsdBalance - minValue) / data.AskPrice1;
            Func <TradingState> rejectUsd    = () => { ex1.TradingState = TradingState.NoUsd; return(ex1.TradingState); };
            Func <TradingState> rejectCrypt  = () => { ex2.TradingState = TradingState.NoCrypt; return(ex2.TradingState); };

            if (ex1.UsdBalance <= ex1.GetMinTradeValue(CurrencyName.USD))
            {
                return(rejectUsd());
            }

            if (ex1.UsdBalance < data.BuyUsdAmount)
            {
                if (ex1.UsdBalance - minValue <= ex1.GetMinTradeValue(CurrencyName.USD))
                {
                    return(rejectUsd());
                }

                data.Amount = reduceAmount();
            }
            else
            {
                if (ex1.UsdBalance - data.BuyUsdAmount <= ex1.GetMinTradeValue(CurrencyName.USD))
                {
                    data.Amount = reduceAmount();
                }
            }
            #endregion
            #region SELL
            var cryptoBalance = ins.GetCryptoBalance(ex2);

            if (cryptoBalance <= ex2.GetMinTradeValue(ins.GetInstrument(), data.BidPrice2))
            {
                return(rejectCrypt());
            }

            if (cryptoBalance < data.Amount)
            {
                data.Amount = cryptoBalance;
            }
            #endregion
            if (amount != data.Amount)
            {
                SetUsdAmounts(ex1, ex2, data);
            }

            ex1.TradingState = ex2.TradingState = TradingState.Ok;
            return(TradingState.Ok);
        }
Example #24
0
        private async void MatchingImpl(IExchange ex1, IExchange ex2, Instrument ins, MatchingData data)
        {
            if (data.TransactionState == TradingState.Ok ||
                data.TransactionState == TradingState.Back)
            {
                if (!_orderBook.TryExecuteOrders(ex1, ex2))
                {
                    return;
                }

                _orderPlacement.ExecuteOrdersAsync(ex1, ex2, data);
            }
            if (data.TransactionState == TradingState.NoPrice ||
                data.TransactionState == TransactionState.Negative ||
                data.TransactionState == TradingState.Reject)
            {
                return;
            }
            if (data.HasRejectedState || data.TransactionState == TradingState.Negative ||
                data.TransactionState == TradingState.Fail12)
            {
                await _dbRepo.SaveMatchingAsync(data);
            }
            else
            {
                _dbRepo.SaveMatchingAsync(data, ex1, ex2).Wait();
            }
        }
Example #25
0
        public TradingState BackTrading(IExchange ex1, IExchange ex2, Instrument ins, MatchingData data)
        {
            data.SetExchange1(ex1);
            data.SetExchange2(ex2);

            InitPrices(data, ins.GetBidPrice(ex2), ins.GetAskPrice(ex1), ins.GetBidOrderAmount(ex2), ins.GetAskOrderAmount(ex1));

            var amount = data.Amount;

            SetUsdAmounts(ex1, ex2, data);

            if (data.ProfitRatio < ProfitRatio)
            {
                return(TradingState.Negative);
            }

            var buyAmount = Math.Min(data.AskAmount, data.BidAmount);

            if (buyAmount < data.Amount)
            {
                return(TradingState.Reject);
            }

            if (data.ProfitRatio > 0)
            {
                data.Amount = Math.Min(buyAmount, data.Amount);
            }

            double avgAmount = (ins.GetCryptoBalance(ex1) + ins.GetCryptoBalance(ex2)) / 2;

            if (buyAmount < avgAmount)
            {
                return(TransactionState.Reject);
            }

            data.Amount = Math.Min(buyAmount, data.Amount);
            SetUsdAmounts(ex1, ex2, data);

            var state = CheckBalancesImpl(ex1, ex2, ins, data);

            if (state != TradingState.Ok)
            {
                return(state);
            }

            return(TradingState.Back);
        }
 public Task SaveMatchingAsync(MatchingData data, IExchange ex1 = null, IExchange ex2 = null)
 {
     return(Task.Run(() => _dbRepo.SaveMatching(data, ex1, ex2)));
 }