private void Request(NetMessageInfo info) { MapPlayer sender = _player.Server[info.Sender.Id]; if (_trading) { sender.View?.FailedTrade(); return; } else if (sender.Trade._requested && sender.Trade._target == _player) { _target = sender; m_state = new TradingState() { InProgress = true, ONE = _player, TWO = sender, ONE_Offer = m_offer, TWO_Offer = sender.Trade.m_offer }; sender.Trade.m_state = m_state; sender.Trade._regected.Destroy(); sender.Trade._trading = _trading = true; UpdateState(); return; } else if (!_requested) { _target = sender; _requested = true; _view.RequestTrade(info.Sender.Id); _regected = new TradeRejector(_player, _target); } }
public void CmdLockOffer() { // validate if (player.state == "TRADING") { state = TradingState.Locked; } }
public void ResetState() { _regected?.Destroy(); m_state = null; _target = null; _trading = false; _regected = null; _requested = false; lock (_lock) m_offer.Clear(); }
public void Cleanup() { // clear all trade related properties offerGold = 0; for (int i = 0; i < offerItems.Count; ++i) { offerItems[i] = -1; } state = TradingState.Free; requestFrom = ""; }
private void BollingerBandStrategy(OHLC ohlc, DateTime date, StrategyParameters parameters) { if (DataPoints.Count < 200) { return; } var rsiPeriod = parameters.RsiPeriod; var rsiThreshold = parameters.RsiThreshold; var stopLossRatio = parameters.StopLossRatio; //Calculate indicators var direction = CalculateMovingAverage(200); var sellSignal = CalculateMovingAverage(5); var rsi = CalculateRelativeStrengthIndex(rsiPeriod); var bb = CalculateBollingerBands(20, 2); var percentB = bb.PercentB; var bandwidth = bb.Bandwidth; //Long Entry //When the price candle closes or is already above 200 day MA and RSI closes below 5 buy //Sell when closes above 5-period moving average if (State == TradingState.Initial) { if (ohlc.High > direction && percentB > 100) { CreateOrder(ohlc, date, "Buy", $"<br/> %b {percentB:N0} <br/> bandwidth {bandwidth:N0} <br/> upper {bb.UpperBand:N0} <br/> lower {bb.LowerBand:N0}"); State = TradingState.MonitoringDownTrend; } } else if (State == TradingState.MonitoringDownTrend || State == TradingState.WaitingToSell) { //Stop loss when BUY order loses more than 2% of its value var buyOrder = Orders.Last(); if ((double)((buyOrder.Price - ohlc.Close) / buyOrder.Price) > stopLossRatio) { CreateOrder(ohlc, date, "Sell", $"Stop Loss <br/> %b {percentB:N0} <br/> bandwidth {bandwidth:N0} <br/> upper {bb.UpperBand:N0} <br/> lower {bb.LowerBand:N0}"); State = TradingState.Initial; return;//Otherwise might sell twice } //Limit profit on downward swing if (percentB < 0) { CreateOrder(ohlc, date, "Sell", $"%b hit over 100 <br/> %b {percentB:N0} <br/> bandwidth {bandwidth:N0} <br/> upper {bb.UpperBand:N0} <br/> lower {bb.LowerBand:N0}"); State = TradingState.Initial; return; } } }
protected override void OnRun() { if (symbol == null || account == null || symbol.ConnectionId != account.ConnectionId) { Log("Incorrect input parameters... Symbol or Account are not specified or they have diffent connections.", StrategyLoggingLevel.Error); return; } threeMaIndicator = Core.Instance.Indicators.BuiltIn.MAS3(ShortMaPeriod, MiddleMaPeriod, LongMaPeriod, BARS_THREE_MA_INTERVAL); historicalData = symbol.GetHistory(period, symbol.HistoryType, DateTime.UtcNow); historicalData.AddIndicator(threeMaIndicator); tradingState = TradingState.ExitMarket; longOrdersCount = 0; shortOrdersCount = 0; maxPeriod = Enumerable.Max(new double[] { ShortMaPeriod, MiddleMaPeriod, LongMaPeriod }); symbol.NewQuote += OnNewQuote; symbol.NewLast += OnNewLast; }
public override void HandleMessage(Yupi.Model.Domain.Habbo session, Yupi.Protocol.Buffers.ClientMessage request, Yupi.Protocol.IRouter router) { string name = request.GetString(); string description = request.GetString(); string roomModel = request.GetString(); int categoryId = request.GetInteger(); int maxVisitors = request.GetInteger(); int tradeStateId = request.GetInteger(); RoomModel model; TradingState tradeState; if (!RoomModel.TryParse(roomModel, out model) || !TradingState.TryFromInt32(tradeStateId, out tradeState)) { return; } NavigatorCategory category = NavigatorRepository.Find(categoryId); if (category.MinRank > session.Info.Rank) { return; } // TODO Filter Name, Description, max visitors RoomData data = new RoomData() { Name = name, Description = description, Model = model, Category = category, UsersMax = maxVisitors, TradeState = tradeState, Owner = session.Info }; RoomRepository.Save(data); router.GetComposer <OnCreateRoomInfoMessageComposer>().Compose(session, data); }
private void DonchienBreakoutStrategy(OHLC ohlc, DateTime date, StrategyParameters parameters) { if (DataPoints.Count < 55) { return; } //Calculate indicators var dca = CalculateDonchianChannel(55); //Long Entry //When closes at DC upper limit if (State == TradingState.Initial) { if (ohlc.Close >= dca.UpperBand) { CreateOrder(ohlc, date, "Buy", $"<br/> Close {ohlc.Close:N0} > Upper {dca.UpperBand:N0}"); State = TradingState.WaitingToSell; } } else if (State == TradingState.WaitingToSell) { //Stop loss when BUY order loses 70 EUR var buyOrder = Orders.Last(); var loss = buyOrder.Price - ohlc.Close; if (loss > 70) { CreateOrder(ohlc, date, "Sell", $"Stop Loss <br/> at loss {loss:N0}"); State = TradingState.Initial; return;//Otherwise might sell twice } //Exit when closes at mid point if (ohlc.Close <= (dca.UpperBand - dca.LowerBand) / 2 + dca.LowerBand) { CreateOrder(ohlc, date, "Sell", $"Closes at mid point"); State = TradingState.Initial; return; } } }
private void RelativeVigorIndexStrategy(OHLC ohlc, DateTime date, StrategyParameters parameters) { if (DataPoints.Count < 40) { return; } //Calculate indicators var rvi = CalculateRelativeVigorIndex(22); var rviBase = CalculateRelativeVigorIndex(10); var percentK = CalculateSlowStochasticOscillatorsPercentK(DataPoints, 17, 6); var percentD = CalculateSlowStochasticOscillatorsPercentD(DataPoints, 13, 17, 6); var envelopeLowerBand = CalculateEnvelopeLowerBand(DataPoints, 10, 0.97); //Long Entry //When the RVI is greater than the signal and //percent K is higher than percent D if (State == TradingState.Initial) { if (rvi > rviBase && percentK > percentD) { CreateOrder(ohlc, date, "Buy", $"<br/> %b {rvi:N0} <br/> > {rviBase:N0} <br/> and {percentK:N0} <br/> > {percentD:N0}"); State = TradingState.WaitingToSell; } } else if (State == TradingState.WaitingToSell || State == TradingState.MonitoringDownTrend) { //Stop loss when BUY order loses 70 EUR var buyOrder = Orders.Last(); //var loss = buyOrder.Price - ohlc.Close; //if (loss > 70) //{ // CreateOrder(ohlc, date, "Sell", $"Stop Loss <br/> at loss {loss:N0}"); // State = TradingState.Initial; // return;//Otherwise might sell twice //} //Exit when it closes over envelope lower band //after closing under envelope lower band if (State == TradingState.WaitingToSell) { if (ohlc.Close < envelopeLowerBand) { State = TradingState.MonitoringDownTrend; } } else if (State == TradingState.MonitoringDownTrend) { if (ohlc.Close > envelopeLowerBand) { CreateOrder(ohlc, date, "Sell", $"Closes over envelope lower band after closing under"); State = TradingState.Initial; return; } } //Limit profit //by selling the asset when it brings in 200 EUR var profit = ohlc.Close - buyOrder.Price; var profitLimit = 200; if (ohlc.Close - buyOrder.Price >= profitLimit) { CreateOrder(ohlc, date, "Sell", $"Profit {profit:N0} exceeded {profitLimit} EUR limit"); State = TradingState.Initial; return; } } }
private void StrategyProcess(MessageQuote message) { if (historicalData.Count <= maxPeriod) { return; } // Calculation of trend Trend trend = (Trend)threeMaIndicator.GetValue(); switch (trend) { case Trend.Up: // Up trend detected. If we were in short position, first closing it if (tradingState == TradingState.EnteredSell) { // If request for closing has been sent, setting the current state - // we have already exit the market Position position = Core.Instance.GetPositionById(currentOrderResult.OrderId, symbol.ConnectionId); if (position == null) { return; } var result = position.Close(); if (result.Status == TradingOperationResultStatus.Success) { tradingState = TradingState.ExitMarket; Log($"{currentOrderResult.Status}. Position was closed.", StrategyLoggingLevel.Trading); } // exitting the program to give some time to // the system for processing the order. Entrance will // be performed on the next quote return; } // If we haven't aleady entered the market, do it if (tradingState != TradingState.EnteredBuy) { var orderPrice = symbol.Bid; if (message is Last last) { orderPrice = last.Price; } if (message is Quote quote) { orderPrice = quote.Ask; } // Sending request for opening long position, and // setting the state - "Entered long position" currentOrderResult = Core.PlaceOrder(new PlaceOrderRequestParameters { Account = account, Symbol = this.symbol, Price = orderPrice, OrderTypeId = OrderType.Market, Quantity = quantity, Side = Side.Buy, }); longOrdersCount++; tradingState = TradingState.EnteredBuy; if (currentOrderResult.Status == TradingOperationResultStatus.Success) { Log($"{currentOrderResult.Status}. Long position was placed.", StrategyLoggingLevel.Trading); } else { Log($"{currentOrderResult.Status}. {currentOrderResult.Message}", StrategyLoggingLevel.Trading); } } break; case Trend.Down: //Down trend detected. If we were in long position, firstly closing it if (tradingState == TradingState.EnteredBuy) { // If request for closing has been sent, setting the current state - // we have already exit the market Position position = Core.Instance.GetPositionById(currentOrderResult.OrderId, symbol.ConnectionId); if (position == null) { return; } var result = position.Close(); if (result.Status == TradingOperationResultStatus.Success) { tradingState = TradingState.ExitMarket; Log($"{currentOrderResult.Status}. Position was closed.", StrategyLoggingLevel.Trading); } // exitting the program to give some time to // the system for processing the order. Entrance will // be performed on the next quote return; } // If we haven't aleady entered the market, do it if (tradingState != TradingState.EnteredSell) { var orderPrice = symbol.Bid; if (message is Last last) { orderPrice = last.Price; } if (message is Quote quote) { orderPrice = quote.Bid; } // Sending request for opening long position, and // if request is sent, then setting the state - "Entered short position" currentOrderResult = Core.PlaceOrder(new PlaceOrderRequestParameters { Account = account, Symbol = this.symbol, Price = orderPrice, OrderTypeId = OrderType.Market, Quantity = quantity, Side = Side.Sell, }); shortOrdersCount++; tradingState = TradingState.EnteredSell; if (currentOrderResult.Status == TradingOperationResultStatus.Success) { Log($"{currentOrderResult.Status}. Short position was placed.", StrategyLoggingLevel.Trading); } else { Log($"{currentOrderResult.Status}. {currentOrderResult.Message}", StrategyLoggingLevel.Trading); } } break; } }
public void CmdAcceptOffer() { // validate // note: distance check already done when starting the trade if (player.state == "TRADING" && state == TradingState.Locked && player.target != null && player.target is Player other) { // other has locked? if (other.trading.state == TradingState.Locked) { // simply accept and wait for the other guy to accept too state = TradingState.Accepted; print("first accept by " + name); } // other has accepted already? then both accepted now, start trade. else if (other.trading.state == TradingState.Accepted) { // accept state = TradingState.Accepted; print("second accept by " + name); // both offers still valid? if (IsOfferStillValid() && other.trading.IsOfferStillValid()) { // both have enough inventory slots? // note: we don't use InventoryCanAdd here because: // - current solution works if both have full inventories // - InventoryCanAdd only checks one slot. here we have // multiple slots though (it could happen that we can // not add slot 2 after we did add slot 1's items etc) if (inventory.SlotsFree() >= InventorySlotsNeededForTrade() && other.inventory.SlotsFree() >= other.trading.InventorySlotsNeededForTrade()) { // exchange the items by first taking them out // into a temporary list and then putting them // in. this guarantees that exchanging even // works with full inventories // take them out Queue <ItemSlot> tempMy = new Queue <ItemSlot>(); foreach (int index in offerItems) { if (index != -1) { ItemSlot slot = inventory.slots[index]; tempMy.Enqueue(slot); slot.amount = 0; inventory.slots[index] = slot; } } Queue <ItemSlot> tempOther = new Queue <ItemSlot>(); foreach (int index in other.trading.offerItems) { if (index != -1) { ItemSlot slot = other.inventory.slots[index]; tempOther.Enqueue(slot); slot.amount = 0; other.inventory.slots[index] = slot; } } // put them into the free slots for (int i = 0; i < inventory.slots.Count; ++i) { if (inventory.slots[i].amount == 0 && tempOther.Count > 0) { inventory.slots[i] = tempOther.Dequeue(); } } for (int i = 0; i < other.inventory.slots.Count; ++i) { if (other.inventory.slots[i].amount == 0 && tempMy.Count > 0) { other.inventory.slots[i] = tempMy.Dequeue(); } } // did it all work? if (tempMy.Count > 0 || tempOther.Count > 0) { Debug.LogWarning("item trade problem"); } // exchange the gold player.gold -= offerGold; other.gold -= other.trading.offerGold; player.gold += other.trading.offerGold; other.gold += offerGold; } } else { print("trade canceled (invalid offer)"); } // clear trade request for both guys. the FSM event will do the // rest requestFrom = ""; other.trading.requestFrom = ""; } } }
public override void HandleMessage(Yupi.Model.Domain.Habbo session, Yupi.Protocol.Buffers.ClientMessage request, Yupi.Protocol.IRouter router) { int roomId = request.GetInteger(); RoomData roomData = RoomRepository.Find(roomId); if (roomData == null || !roomData.HasOwnerRights(session.Info)) { return; } // TODO Filter string newName = request.GetString(); // TODO Magic constant if (newName.Length > 2) { roomData.Name = newName; } // TODO Filter roomData.Description = request.GetString(); int stateId = request.GetInteger(); RoomState state; if (RoomState.TryFromInt32(stateId, out state)) { roomData.State = state; } roomData.Password = request.GetString(); roomData.UsersMax = request.GetInteger(); int categoryId = request.GetInteger(); FlatNavigatorCategory category = NavigatorCategoryRepository.Find(categoryId); if (category != null && category.MinRank <= session.Info.Rank) { roomData.Category = category; } int tagCount = request.GetInteger(); if (tagCount <= 2) { roomData.Tags.Clear(); IRepository <Tag> TagRepository = DependencyFactory.Resolve <IRepository <Tag> > (); for (int i = 0; i < tagCount; i++) { string tagValue = request.GetString().ToLower(); Tag tag = TagRepository.Find(tagValue); if (tag == null) { tag = new Tag(tagValue); } roomData.Tags.Add(tag); } } TradingState tradeState; if (TradingState.TryFromInt32(request.GetInteger(), out tradeState)) { roomData.TradeState = tradeState; } roomData.AllowPets = request.GetBool(); roomData.AllowPetsEating = request.GetBool(); roomData.AllowWalkThrough = request.GetBool(); bool hideWall = request.GetBool(); int wallThickness = request.GetInteger(); int floorThickness = request.GetInteger(); if (session.Info.Subscription.HasLevel(ClubLevel.HC)) { roomData.HideWall = hideWall; roomData.WallThickness = wallThickness; roomData.FloorThickness = floorThickness; } else { roomData.HideWall = false; roomData.WallThickness = 0; roomData.FloorThickness = 0; } RoomModerationRight right; if (RoomModerationRight.TryFromInt32(request.GetInteger(), out right)) { roomData.ModerationSettings.WhoCanMute = right; } if (RoomModerationRight.TryFromInt32(request.GetInteger(), out right)) { roomData.ModerationSettings.WhoCanKick = right; } if (RoomModerationRight.TryFromInt32(request.GetInteger(), out right)) { roomData.ModerationSettings.WhoCanBan = right; } ChatType chatType; if (ChatType.TryFromInt32(request.GetInteger(), out chatType)) { roomData.Chat.Type = chatType; } ChatBalloon chatBalloon; if (ChatBalloon.TryFromInt32(request.GetInteger(), out chatBalloon)) { roomData.Chat.Balloon = chatBalloon; } ChatSpeed chatSpeed; if (ChatSpeed.TryFromInt32(request.GetInteger(), out chatSpeed)) { roomData.Chat.Speed = chatSpeed; } int maxDistance = request.GetInteger(); if (roomData.Chat.isValidDistance(maxDistance)) { roomData.Chat.SetMaxDistance(maxDistance); } FloodProtection floodProtection; if (FloodProtection.TryFromInt32(request.GetInteger(), out floodProtection)) { roomData.Chat.FloodProtection = floodProtection; } request.GetBool(); //TODO allow_dyncats_checkbox router.GetComposer <RoomSettingsSavedMessageComposer>().Compose(session, roomData.Id); Room room = RoomManager.GetIfLoaded(roomData); if (room != null) { room.EachUser(x => { x.Router.GetComposer <RoomUpdateMessageComposer>().Compose(x, roomData.Id); x.Router.GetComposer <RoomFloorWallLevelsMessageComposer>().Compose(x, roomData); x.Router.GetComposer <RoomChatOptionsMessageComposer>().Compose(x, roomData); x.Router.GetComposer <RoomDataMessageComposer>().Compose(x, roomData, x.Info, true, true); }); } }