Exemplo n.º 1
0
        public void TestService()
        {
            CreateOrderParameters para = new CreateOrderParameters()
            {
                AppOrderAmount = 1,
                AppOrderDesc   = "测试",
                AppOrderID     = sss,
                AppOrderTime   = DateTime.Now.ToJITFormatString(),
                PayChannelID   = 16,
                MobileNO       = "18019438327"
            };
            TradeRequest request = new TradeRequest()
            {
                AppID      = 1,
                ClientID   = "27",
                Parameters = para,
                UserID     = "1111"
            };
            string parameter = string.Format("action=CreateOrder&request={1}", Url, request.ToJSON());
            //parameter = "action=CreateOrder&request={\"AppID\":1,\"ClientID\":\"e703dbedadd943abacf864531decdac1\",\"UserID\":\"00193aeff94341a1a8f64e224c7c249c\",\"Token\":null,\"Parameters\":{\"PayChannelID\":3,\"AppOrderID\":\"61ebfd4cbb1b4716b40605845cc761cd\",\"AppOrderTime\":\"2014-01-17 09:46:30 562\",\"AppOrderAmount\":1,\"AppOrderDesc\":\"jitmarketing\",\"Currency\":1,\"MobileNO\":\"\",\"ReturnUrl\":\"http://www.o2omarketing.cn:9004/HtmlApp/LJ/html/pay_success.html?orderId=61ebfd4cbb1b4716b40605845cc761cd\",\"DynamicID\":null,\"DynamicIDType\":null}}";
            var data = Encoding.GetEncoding("utf-8").GetBytes(parameter);
            var res  = GetResponseStr(Url, data).DeserializeJSONTo <TradeResponse>();

            Console.WriteLine(res.ToJSON());
        }
Exemplo n.º 2
0
    private void _applyTrade(TradeRequest request)
    {
        PlayerState player = _playerGroup.GetPlayerByIndex(request.playerIndex);
        CardData    card   = _assetStash[request.playerIndex];

        player.hand.SetCard(request.handSlot, card);
    }
Exemplo n.º 3
0
    private void _undoTrade(TradeRequest request)
    {
        PlayerState player = _playerGroup.GetPlayerByIndex(request.playerIndex);
        CardData    card   = player.hand.PopCard(request.handSlot);

        _assetStash[request.playerIndex] = card;
    }
Exemplo n.º 4
0
        public void OnChatMessage(ChatMessage msg)
        {
            if (msg.Channel != DataTypes.Enums.ChatMessageChannel.Private)
            {
                return;
            }

            var match = _tradeRequestRegex.Match(msg.Message);

            if (!match.Success)
            {
                return;
            }

            // TODO
            bool isCurrencyTrade = false;

            TradeRequest request = new TradeRequest
            {
                PlayerName         = msg.Sender,
                IsOutgoing         = msg.Message.StartsWith("@To"),
                IsCurrencyExchange = isCurrencyTrade,

                ItemName     = match.Groups[2].Value,
                Price        = int.Parse(match.Groups[3].Value),
                CurrencyName = match.Groups[4].Value,
                StashTabName = match.Groups[6].Value,
                ItemPosition = new System.Drawing.Point(int.Parse(match.Groups[7].Value), int.Parse(match.Groups[8].Value))
            };

            Messenger.Default.Send(new Messages.IncomingTradeMessage(request));
        }
Exemplo n.º 5
0
        public async Task <ActionResult <Operation> > Get(TradeRequest request)
        {
            long id             = request.ReceiverId;
            var  ReceiverClient = await _context.Clients.FindAsync(id);

            id = request.SenderId;
            var ChallengeClient = await _context.Clients.FindAsync(id);

            if (ChallengeClient == null || ReceiverClient == null)
            {
                return(NotFound());
            }

            ChallengeClient.Balance -= request.Value;
            ReceiverClient.Balance  += request.Value;

            var operation = new Operation {
                Sender   = ChallengeClient.Id.ToString(),
                Receiver = ReceiverClient.Id.ToString(),
                Type     = "Trade",
                Value    = request.Value.ToString(),
                Date     = DateTime.Now
            };

            _context.Operations.Add(operation);

            if (Hasher.Verify(request.Password, ChallengeClient.Password))
            {
                await _context.SaveChangesAsync();

                return(operation);
            }

            return(Unauthorized());
        }
    public static void RequestTradeRoute(ShipModel model, Action <ShipModel, Items, StructureModel[], bool> callback)
    {
        TradeRequest newRequest = new TradeRequest(model, callback);

        instance.tradeRequestQueue.Enqueue(newRequest);
        instance.TryProcessNext();
    }
Exemplo n.º 7
0
        private static void StartNextAdminTradeDownload(string segment, uint messageTag, int?messageType)
        {
            //Set reply and EOD flags to false
            UtilityLoginDetails.GETInstance.PersonalReplyReceived = false;
            UtilityLoginDetails.GETInstance.EndofdownloadReceived = false;

            _tradeRequest = new TradeRequest();
            _tradeRequest.AppBeginSequenceNum = 1;
            _tradeRequest.AppEndSequenceNum   = 1;
            _tradeRequest.Exchange            = 1;
            _tradeRequest.Market = 1;
            //_tradeRequest.MessageTag = MemoryManager.GetMesageTag();
            _tradeRequest.PartitionID   = 1;
            _tradeRequest.ReservedField = 0;
            _tradeRequest.Hour          = "0";
            _tradeRequest.Minute        = "0";
            _tradeRequest.Second        = "0";
            _tradeRequest.Filler        = segment;

            if (segment == "E")
            {
                _tradeRequest.MessageTag = (uint)Enumerations.Trade.AdminTradeRequestMsgTag.EQTYSEGINDICATOR;
            }
            if (segment == "D")
            {
                _tradeRequest.MessageTag = (uint)Enumerations.Trade.AdminTradeRequestMsgTag.DERISEGINDICATOR;
            }
            if (segment == "C")
            {
                _tradeRequest.MessageTag = (uint)Enumerations.Trade.AdminTradeRequestMsgTag.CURRSEGINDICATOR;
            }

            _tradeRequestProcessor = new TradeRequestProcessor(new AdminTradePersonalDownload());
            _tradeRequestProcessor.ProcessRequest(_tradeRequest, (int)TradeTypeDownload.TradeRequest);
        }
Exemplo n.º 8
0
        /// <summary>
        /// 获取单笔交易的详细信息
        /// </summary>
        public static void GetTrade()
        {
            //202005213524461
            TradeRequest request = new TradeRequest()
            {
                tid = "202005213524461"
            };
            Dictionary <string, string> keyValuePairs = SignHelper.GetDictionary <TradeRequest>(request);

            keyValuePairs.Add("app_key", appKey);
            keyValuePairs.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            string sign = SignHelper.SignTopRequest(keyValuePairs, "md5", appSecret);

            string postUrl = url + WXAppConstants.tradeUrl;
            string param   = string.Empty;

            foreach (var kv in keyValuePairs)
            {
                param += kv.Key + "=" + kv.Value + "&";
            }
            param += "sign=" + sign;

            var result = HttpHelper.HttpGet(postUrl, param);

            try
            {
                var response = JsonConvert.DeserializeObject <TradeResponse>(result, new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Ignore
                });
            }
            catch (Exception ex)
            {
            }
        }
        public override IMessage ToMessage(object objectToConvert, ISession session)
        {
            TradeRequest tradeRequest = objectToConvert as TradeRequest;

            if (tradeRequest == null)
            {
                throw new MessageConversionException("TradeRequestConverter can not convert object of type " +
                                                     objectToConvert.GetType());
            }

            try
            {
                IMapMessage mm = session.CreateMapMessage();


                mm.Body.SetString("accountName", tradeRequest.AccountName);
                mm.Body.SetBool("buyRequest", tradeRequest.BuyRequest);
                mm.Body.SetString("orderType", tradeRequest.OrderType);
                mm.Body.SetDouble("price", tradeRequest.Price);
                mm.Body.SetLong("quantity", tradeRequest.Quantity);
                mm.Body.SetString("requestId", tradeRequest.RequestId);
                mm.Body.SetString("ticker", tradeRequest.Ticker);
                mm.Body.SetString("username", tradeRequest.UserName);

                return(mm);
            } catch (Exception e)
            {
                throw new MessageConversionException("Could not convert TradeRequest to message", e);
            }
        }
Exemplo n.º 10
0
        private void ShowTradeWindow(decimal price, TradeTypeEnum way)
        {
            ITradeRequest sellTrade = new TradeRequest
            {
                Amount    = 1,
                Pair      = CurrentPair,
                Rate      = price,
                TradeType = way
            };

            var editTradeViewModel = new EditTradeViewModel(sellTrade, tradingConfigurations, btceModels.AccountInfo);
            var editTradeView      = new EditTrade();

            editTradeView.DataContext = editTradeViewModel;

            editTradeViewModel.CancelCommand = new RelayCommand((parameters) =>
            {
                editTradeView.Close();
            });

            editTradeViewModel.OkCommand = new RelayCommand((parameters) =>
            {
                btceTradeApi.MakeTrade(editTradeViewModel.TradeRequest);
                editTradeView.Close();
            });


            editTradeView.ShowDialog();
        }
Exemplo n.º 11
0
        /// <summary>
        /// 验证订单是否支付
        /// </summary>
        /// <param name="pRequest"></param>
        /// <returns></returns>
        internal static bool IsOrderPaid(TradeRequest pRequest)
        {
            var para   = pRequest.GetParameter <QueryOrderByAppInfoParameters>();
            var bll    = new AppOrderBLL(pRequest.GetUserInfo());
            var entity = bll.GetByAppInfo(pRequest.AppID.Value, para.AppOrderID, pRequest.ClientID);

            return(entity.Status == 2);
        }
Exemplo n.º 12
0
 public void Send(TradeRequest tradeRequest)
 {
     EmsTemplate.ConvertAndSendWithDelegate(tradeRequest, delegate(Message message)
     {
         message.ReplyTo       = defaultReplyToQueue;
         message.CorrelationID = new Guid().ToString();
         return(message);
     });
 }
Exemplo n.º 13
0
    public static TradeRequest Create(int playerIndex, int teamIndex, int handSlot)
    {
        TradeRequest trade = new TradeRequest();

        trade.playerIndex = playerIndex;
        trade.teamIndex   = teamIndex;
        trade.handSlot    = handSlot;
        return(trade);
    }
Exemplo n.º 14
0
        public static AddTradeRequestCommand Create(TradeEscrow escrow, TradeRequest request)
        {
            AddTradeRequestCommand command = new AddTradeRequestCommand();

            command.escrow  = escrow;
            command.request = request;

            return(command);
        }
 void TryProcessNext()
 {
     if (!isProcessingPath && tradeRequestQueue.Count > 0)
     {
         currentTradeRequest = tradeRequestQueue.Dequeue();
         isProcessingPath    = true;
         tradeRoute.StartTradeRouteSearch(currentTradeRequest.model);
     }
 }
Exemplo n.º 16
0
    public void AddAsset(TradeRequest request)
    {
        PlayerState player        = _playerGroup.GetPlayerByIndex(request.playerIndex);
        CardData    card          = player.hand.PopCard(request.handSlot);
        PlayerState partnerPlayer = _teamCollection.GetPartner(request.teamIndex, request.playerIndex);

        _assetStash[partnerPlayer.index] = card;
        _escrow.Add(request);
    }
 public void Send(TradeRequest tradeRequest)
 {
     RabbitTemplate.ConvertAndSend(tradeRequest, delegate(Message message)
     {
         message.MessageProperties.ReplyToAddress = new Address(defaultReplyToQueue);
         message.MessageProperties.CorrelationId  = new Guid().ToByteArray();
         return(message);
     });
 }
Exemplo n.º 18
0
        public async Task TradeAsync(TradeRequest request, Func <TradeResponse, Task> responseHandler)
        {
            _logger.LogInformation("Trade {}", request);

            var resp = new TradeResponse()
            {
                RequestId = request.RequestId
            };

            try
            {
                if (!await AcquireGameLock(request.GameId, request.RequestId, TimeSpan.FromSeconds(30)))
                {
                    resp.ErrorMessage = "Timed out while acquiring game lock";
                    await responseHandler(resp);

                    return;
                }

                var gameState = await _dbContext.GameStates
                                .FirstOrDefaultAsync(x => x.GameId == request.GameId);

                if (gameState == null)
                {
                    resp.ErrorMessage = "GameId not found";
                    await responseHandler(resp);

                    return;
                }

                var gameEngine = new GameEngine(_loggerProvider, _dbContext, _cardRepo);
                gameEngine.GameState = gameState;

                if (gameEngine.GameState.IsFinished)
                {
                    resp.ErrorMessage = "Game is finished";
                    await responseHandler(resp);

                    return;
                }

                List <Models.Trade> trades;
                (resp.IsSuccess, resp.ErrorMessage, trades) = await gameEngine.Trade(request);
                await responseHandler(resp);

                if (resp.IsSuccess)
                {
                    InvokeOnGameUpdate(MakeGameUpdateResponse(gameEngine.GameState));
                    InvokeOnTradeUpdate(null, MakeTradeUpdateResponse(gameEngine.GameState.GameId, trades));
                }
            }
            finally
            {
                ReleaseGameLock(request.GameId, request.RequestId);
            }
        }
 public void Send(TradeRequest tradeRequest)
 {
     // post process message from conversion before sending
     MessageQueueTemplate.ConvertAndSend(tradeRequest, delegate(Message message)
     {
         message.ResponseQueue = GetResponseQueue();
         message.AppSpecific   = random.Next();
         return(message);
     });
 }
Exemplo n.º 20
0
        public async Task <(bool, string, List <Trade>)> Trade(TradeRequest request)
        {
            var ret = TradeInternal(request);

            if (ret.IsSuccess)
            {
                await _dbContext.SaveChangesAsync();
            }
            return(ret);
        }
Exemplo n.º 21
0
        /// <summary>
        /// 更新微信反馈
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        internal static object WXGetUpdateFeedBackUrl(TradeRequest request)
        {
            WXGetUpdateFeedBackReqPara para = request.GetParameter <WXGetUpdateFeedBackReqPara>();
            var    channelBll = new PayChannelBLL(new Utility.BasicUserInfo());
            var    channel    = channelBll.GetByID(para.PayChannelID);
            var    WXChannel  = channel.ChannelParameters.DeserializeJSONTo <WeiXinPayChannel>();
            string url        = WeiXinPayGateway.GetUpdateFeedBackUrl(WXChannel, para.FeedBackID, para.OpenID);

            return(new { Url = url });
        }
Exemplo n.º 22
0
        /// <summary>
        /// 创建微信支付NativePay连接
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        internal static object CreateWXNativePayUrl(TradeRequest request)
        {
            CreateWXNativePayUrlReqPara para = request.GetParameter <CreateWXNativePayUrlReqPara>();
            var             channelBll       = new PayChannelBLL(new Utility.BasicUserInfo());
            var             channel          = channelBll.GetByID(para.PayChannelID);
            var             WXChannel        = channel.ChannelParameters.DeserializeJSONTo <WeiXinPayChannel>();
            NativePayHelper req = new NativePayHelper(WXChannel);

            return(new { NativePayUrl = req.GenerateNativeUrl(para.ProductID) });
        }
Exemplo n.º 23
0
        public TradeResponse ExecuteTradeRequest(TradeRequest request)
        {
            TradeResponse response = new TradeResponse();

            response.OrderType          = request.OrderType;
            response.Price              = CalculatePrice(request.Ticker, request.Quantity, request.OrderType, request.Price, request.UserName);
            response.Quantity           = request.Quantity;
            response.Ticker             = request.Ticker;
            response.ConfirmationNumber = new Guid().ToString();
            return(response);
        }
Exemplo n.º 24
0
    public void RemoveAsset(TradeRequest request)
    {
        PlayerState player        = _playerGroup.GetPlayerByIndex(request.playerIndex);
        PlayerState partnerPlayer = _teamCollection.GetPartner(request.teamIndex, request.playerIndex);
        CardData    card          = _assetStash[partnerPlayer.index];

        player.hand.SetCard(request.handSlot, card);

        _assetStash.Remove(partnerPlayer.index);
        _escrow.Remove(request);
    }
Exemplo n.º 25
0
 public bool Equals(TradeRequest other)
 {
     if (ReferenceEquals(null, other))
     {
         return(false);
     }
     if (ReferenceEquals(this, other))
     {
         return(true);
     }
     return(Equals(other.ticker, ticker) && other.quantity == quantity && other.price == price && Equals(other.orderType, orderType) && Equals(other.accountName, accountName) && other.buyRequest.Equals(buyRequest) && Equals(other.userName, userName) && Equals(other.requestId, requestId));
 }
Exemplo n.º 26
0
        private async Task <ExternalTrade> ExecuteLimitOrderAsync(string assetPairId, decimal volume, decimal?price,
                                                                  Side side)
        {
            string instrument = await GetInstrumentAsync(assetPairId);

            var request = new RequestForQuoteRequest(instrument, side, volume);

            RequestForQuoteResponse response;

            Trade trade = await WrapAsync(async() =>
            {
                _log.InfoWithDetails("Get quote request", request);

                response = await _client.RequestForQuoteAsync(request);

                _log.InfoWithDetails("Get quote response", response);

                if (price.HasValue)
                {
                    if (side == Side.Sell && price.Value > response.Price)
                    {
                        throw new NotEnoughLiquidityException();
                    }

                    if (side == Side.Buy && price.Value < response.Price)
                    {
                        throw new NotEnoughLiquidityException();
                    }
                }

                var tradeRequest = new TradeRequest(response);

                _log.InfoWithDetails("Execute trade request", tradeRequest);

                Trade tradeResponse = await _client.TradeAsync(tradeRequest);

                _log.InfoWithDetails("Execute trade response", tradeResponse);

                return(tradeResponse);
            });

            return(new ExternalTrade
            {
                Id = trade.TradeId,
                LimitOrderId = trade.Order,
                AssetPairId = trade.Instrument,
                Type = trade.Side == Side.Sell ? TradeType.Sell : TradeType.Buy,
                Time = trade.Created,
                Price = trade.Price,
                Volume = trade.Quantity,
                RequestId = trade.RfqId
            });
        }
Exemplo n.º 27
0
        /// <inheritdoc/>
        public void HandlePacket(Player player, Span <byte> packet)
        {
            TradeRequest message = packet;
            Player       partner = player.GetObservingPlayerWithId(message.PlayerId);

            if (partner == null)
            {
                player.ViewPlugIns.GetPlugIn <IShowMessagePlugIn>()?.ShowMessage("Trade partner not found.", MessageType.BlueNormal);
                return;
            }

            this.requestAction.RequestTrade(player, partner);
        }
Exemplo n.º 28
0
        public void SendTradeRequest()
        {
            TradeRequest tradeRequest = new TradeRequest();

            tradeRequest.AccountName = "ACCT-123";
            tradeRequest.BuyRequest  = true;
            tradeRequest.OrderType   = "MARKET";
            tradeRequest.Quantity    = 314000000;
            tradeRequest.RequestID   = "REQ-1";
            tradeRequest.Ticker      = "CSCO";
            tradeRequest.UserName    = "******";

            stockService.Send(tradeRequest);
        }
Exemplo n.º 29
0
        private async void ExecuteOrderCheck(object obj)
        {
            var request = TradeRequest.GetMqlTradeRequest();
            MqlTradeCheckResult result = null;
            var retVal = await Execute(() =>
            {
                var ok = _mtApiClient.OrderCheck(request, out result);
                return(ok);
            });

            var message = retVal ? $"OrderCheck: success. {result}" : $"OrderCheck: fail. {result}";

            AddLog(message);
        }
Exemplo n.º 30
0
        private void _notifyTrader(Order order)
        {
            _log.Debug("通知交易端下单 策略ID:{0}, 代码:{1}, 证券类别: {2}, 价格:{3}, 数量:{4}", Desc.Id, order.Symbol);

            TradeRequest req = new TradeRequest();

            req.OrderType      = order.Type;
            req.TradeInterface = TradeInterface.THS;
            req.TradeType      = TradeType.ALGO;

            req.SecuritiesOrder = order;

            tradeActor.Tell(req); // TODO: 改为ASK?
        }
Exemplo n.º 31
0
 public bool Equals(TradeRequest other)
 {
     if (ReferenceEquals(null, other)) return false;
     if (ReferenceEquals(this, other)) return true;
     return Equals(other.ticker, ticker) && other.quantity == quantity && other.price == price && Equals(other.orderType, orderType) && Equals(other.accountName, accountName) && other.buyRequest.Equals(buyRequest) && Equals(other.userName, userName) && Equals(other.requestId, requestId);
 }