internal TradeData(TradeEntry entry) { if (entry == null) { throw new ArgumentNullException(nameof(entry)); } this.Tag = entry.Tag != null?entry.Tag.ToString() : string.Empty; this.Type = TradeTypeFromTradeRecordType(entry.Type); this.Side = entry.Side; this.Symbol = entry.Symbol; this.Volume = entry.Volume; this.MaxVisibleVolume = entry.MaxVisibleVolume; this.Price = entry.Price; this.StopPrice = entry.StopPrice; this.Commission = entry.Commission; this.AgentCommission = entry.AgentCommission; this.Swap = entry.Swap; //this.Rate = entry.StaticMarginRate; this.ProfitStatus = entry.ProfitStatus; this.MarginStatus = entry.MarginStatus; this.Profit = entry.Profit; this.Margin = entry.Margin; }
private bool AddToTradeQueue(PK8 pk8, int code, IUser user, RequestSignificance sig, PokeRoutineType type, out string msg) { // var user = e.WhisperMessage.UserId; var userID = (ulong)user.Id; var name = user.ScreenName; var trainer = new PokeTradeTrainerInfo(name); var notifier = new TwitterTradeNotifier <PK8>(pk8, trainer, code, name, client, user, Hub.Config.Twitter); var tt = type == PokeRoutineType.SeedCheck ? PokeTradeType.Seed : PokeTradeType.Specific; var detail = new PokeTradeDetail <PK8>(pk8, trainer, notifier, tt, code, sig == RequestSignificance.Favored); var trade = new TradeEntry <PK8>(detail, userID, type, name); var added = Info.AddToTradeQueue(trade, userID, sig == RequestSignificance.Sudo); if (added == QueueResultAdd.AlreadyInQueue) { msg = $"@{name}: Sorry, you are already in the queue."; return(false); } var position = Info.CheckPosition(userID, type); msg = $"@{name}: Added to the {type} queue, unique ID: {detail.ID}. Current Position: {position.Position}"; var botct = Info.Hub.Bots.Count; if (position.Position > botct) { var eta = Info.Hub.Config.Queues.EstimateDelay(position.Position, botct); msg += $". Estimated: {eta:F1} minutes."; } return(true); }
private static void RemoveAndCheck <T>(TradeQueueInfo <T> info, TradeEntry <T> trade, PokeRoutineExecutorBase routine) where T : PKM, new() { var result = info.Remove(trade); result.Should().BeTrue(); routine.Should().NotBeNull(); }
public void Delete <T>(dynamic tpe) { { switch (typeof(T).Name) { case "TradeEntry": TradeEntry tpo = tpe; context.tradeEntry.Remove(context.tradeEntry.First(trdE => trdE.id == tpo.id)); break; case "InstrumentPerformance": InstrumentPerformance tpo_1 = tpe; context.instrumentPerformance.Remove(context.instrumentPerformance.First(tpx => tpx.id == tpo_1.id)); break; case "UserRecord": UserRecord tpo_2 = tpe; context.userRecord.Remove(context.userRecord.First(tpx => tpx.id == tpo_2.id)); break; default: break; } context.SaveChanges(); } }
private bool AddToTradeQueue(PK8 pk8, int code, OnWhisperReceivedArgs e, bool sudo, PokeRoutineType type, out string msg) { // var user = e.WhisperMessage.UserId; var userID = ulong.Parse(e.WhisperMessage.UserId); var name = e.WhisperMessage.DisplayName; var trainer = new PokeTradeTrainerInfo(name); var notifier = new TwitchTradeNotifier <PK8>(pk8, trainer, code, e.WhisperMessage.Username, client, Channel, Hub.Config.Twitch); var tt = type == PokeRoutineType.SeedCheck ? PokeTradeType.Seed : PokeTradeType.Specific; var detail = new PokeTradeDetail <PK8>(pk8, trainer, notifier, tt, code: code); var trade = new TradeEntry <PK8>(detail, userID, type, name); var added = Info.AddToTradeQueue(trade, userID, sudo); if (added == QueueResultAdd.AlreadyInQueue) { msg = "Sorry, you are already in the queue."; return(false); } var position = Info.CheckPosition(userID, type); msg = $"@{name}: Added to the {type} queue, unique ID: {detail.ID}. Current Position: {position.Position}"; var botct = Info.Hub.Bots.Count; if (position.Position > botct) { var eta = Info.Hub.Config.Queues.EstimateDelay(position.Position, botct); msg += $". Estimated: {eta:F1} minutes."; } return(true); }
private static void RemoveAndCheck(TradeQueueInfo <PK8> info, TradeEntry <PK8> trade, PokeRoutineExecutor routine) { var result = info.Remove(trade); result.Should().BeTrue(); routine.Should().NotBeNull(); }
public TradeOrderCrate(Mobile from, TradeEntry entry) : base(Utility.Random(0xE3C, 4)) { Owner = from; Entry = entry; Expires = DateTime.UtcNow + TimeSpan.FromHours(CityTradeSystem.CrateDuration); }
/** * getTradeExample * Get Recently Trades */ public static void GetTradeExample() { /***Initialize the calling object*/ IdaxApiRestClient idaxApiRestClient = IdaxConfig.init(); /**Request parameter encapsulation**/ string symbol = IdaxApiConstants.ETH_BTC; /**Call remote interface**/ TradeEntry tradeEntry = idaxApiRestClient.getTradeEntry(symbol); }
static bool TryProcessAsTradeRecord(TradeEntry entry, ICollection<TradeRecord> records) { var record = entry.Tag as TradeRecord; if (record == null) return false; record.Profit = entry.Profit; records.Add(record); return true; }
private static bool AddToTradeQueue(SocketCommandContext context, T pk, int code, string trainerName, RequestSignificance sig, PokeRoutineType type, PokeTradeType t, SocketUser trader, out string msg, int catchID = 0) { var user = trader; var userID = user.Id; var name = user.Username; var trainer = new PokeTradeTrainerInfo(trainerName, userID); var notifier = new DiscordTradeNotifier <T>(pk, trainer, code, user); var detail = new PokeTradeDetail <T>(pk, trainer, notifier, t, code, sig == RequestSignificance.Favored); var trade = new TradeEntry <T>(detail, userID, type, name); var hub = SysCord <T> .Runner.Hub; var Info = hub.Queues.Info; var added = Info.AddToTradeQueue(trade, userID, sig == RequestSignificance.Owner); if (added == QueueResultAdd.AlreadyInQueue) { msg = "Sorry, you are already in the queue."; return(false); } if (detail.Type == PokeTradeType.TradeCord) { TradeCordHelper <T> .TradeCordTrades.Add(trader.Id, catchID); } var position = Info.CheckPosition(userID, type); var ticketID = ""; if (TradeStartModule <T> .IsStartChannel(context.Channel.Id)) { ticketID = $", unique ID: {detail.ID}"; } var pokeName = ""; if ((t == PokeTradeType.Specific || t == PokeTradeType.TradeCord || t == PokeTradeType.SupportTrade || t == PokeTradeType.Giveaway) && pk.Species != 0) { pokeName = $" Receiving: {(t == PokeTradeType.SupportTrade && pk.Species != (int)Species.Ditto && pk.HeldItem != 0 ? $"{(Species)pk.Species} ({ShowdownParsing.GetShowdownText(pk).Split('@','\n')[1].Trim()})" : $"{(Species)pk.Species}")}."; } msg = $"{user.Mention} - Added to the {type} queue{ticketID}. Current Position: {position.Position}.{pokeName}"; var botct = Info.Hub.Bots.Count; if (position.Position > botct) { var eta = Info.Hub.Config.Queues.EstimateDelay(position.Position, botct); msg += $" Estimated: {eta:F1} minutes."; } return(true); }
public static void fixBadDate(ref TradeEntry trdA) { DateTime FutureDate = new DateTime(2050, 1, 1); DateTime badDate = new DateTime(1970, 1, 1); if (trdA.dateClosed < badDate) { trdA.dateClosed = FutureDate; } if (trdA.dateEntered < badDate) { trdA.dateEntered = badDate; } }
static bool TryProcessAsPosition(TradeEntry entry, ICollection<Position> positions) { var position = entry.Tag as Position; if (position == null) return false; if (entry.Profit.HasValue) position.Profit = position.Profit.GetValueOrDefault() + entry.Profit; // some magic; see Calculate method of state calcualtor if (entry.Side == TradeRecordSide.Buy) positions.Add(position); return true; }
private static bool AddToTradeQueue(this SocketCommandContext Context, PK8 pk8, int code, string trainerName, bool sudo, PokeRoutineType type, PokeTradeType t, out string msg) { var user = Context.User; var userID = user.Id; var name = user.Username; var trainer = new PokeTradeTrainerInfo(trainerName); var notifier = new DiscordTradeNotifier <PK8>(pk8, trainer, code, Context); var detail = new PokeTradeDetail <PK8>(pk8, trainer, notifier, t, code: code); var trade = new TradeEntry <PK8>(detail, userID, type, name); var hub = SysCordInstance.Self.Hub; var Info = hub.Queues.Info; var added = Info.AddToTradeQueue(trade, userID, sudo); if (added == QueueResultAdd.AlreadyInQueue) { msg = "Sorry, you are already in the queue."; return(false); } var position = Info.CheckPosition(userID, type); var ticketID = ""; if (TradeStartModule.IsStartChannel(Context.Channel.Id)) { ticketID = $", unique ID: {detail.ID}"; } var pokeName = ""; if (t == PokeTradeType.Specific || t == PokeTradeType.EggRoll && pk8.Species != 0) { pokeName = $" Receiving: {(t == PokeTradeType.EggRoll ? "Mysterious egg" : hub.Config.Trade.ItemMuleSpecies == (Species)pk8.Species && pk8.HeldItem != 0 ? $"{(Species)pk8.Species + " (" + ShowdownSet.GetShowdownText(pk8).Split('@','\n')[1].Trim() + ")"}" : $"{(Species)pk8.Species}")}."; } msg = $"{user.Mention} - Added to the {type} queue{ticketID}. Current Position: {position.Position}.{pokeName}"; var botct = Info.Hub.Bots.Count; if (position.Position > botct) { var eta = Info.Hub.Config.Queues.EstimateDelay(position.Position, botct); msg += $" Estimated: {eta:F1} minutes."; } return(true); }
private static bool AddToTradeQueue(this SocketCommandContext Context, PK8 pk8, int code, string trainerName, RequestSignificance sig, PokeRoutineType type, PokeTradeType t, SocketUser trader, out string msg) { var user = trader; var userID = user.Id; var name = user.Username; var trainer = new PokeTradeTrainerInfo(trainerName); var notifier = new DiscordTradeNotifier <PK8>(pk8, trainer, code, user); var detail = new PokeTradeDetail <PK8>(pk8, trainer, notifier, t, code: code, sig == RequestSignificance.Favored); var trade = new TradeEntry <PK8>(detail, userID, type, name); var hub = SysCordInstance.Self.Hub; var Info = hub.Queues.Info; var added = Info.AddToTradeQueue(trade, userID, sig == RequestSignificance.Sudo); if (added == QueueResultAdd.AlreadyInQueue) { msg = "Sorry, you are already in the queue."; return(false); } var position = Info.CheckPosition(userID, type); var ticketID = ""; if (TradeStartModule.IsStartChannel(Context.Channel.Id)) { ticketID = $", unique ID: {detail.ID}"; } var pokeName = ""; if (t == PokeTradeType.Specific && pk8.Species != 0) { pokeName = $" Receiving: {(Species)pk8.Species}."; } msg = $"{user.Mention} - Added to the {type} queue{ticketID}. Current Position: {position.Position}.{pokeName}"; var botct = Info.Hub.Bots.Count; if (position.Position > botct) { var eta = Info.Hub.Config.Queues.EstimateDelay(position.Position, botct); msg += $" Estimated: {eta:F1} minutes."; } return(true); }
public CalculatorOrder(TradeEntry entry) { this.entry = entry; if (this.entry.Owner.Type != AccountType.Cash) { this.roundMargin = this.entry.Owner.RoundingService.RoundMargin; this.roundProfit = this.entry.Owner.RoundingService.RoundProfit; } else { var assetCurrency = this.entry.Side == TradeRecordSide.Buy ? this.entry.SymbolEntry.ProfitCurrency : this.entry.SymbolEntry.MarginCurrency; this.roundMargin = o => this.entry.Owner.RoundingService.RoundMargin(assetCurrency, o); this.roundProfit = o => this.entry.Owner.RoundingService.RoundProfit(assetCurrency, o); } }
void OnAddTrade(object sender, EventArgs e) { var account = this.GetCurrentAccountEntry(); if (account == null) { return; } var entry = new TradeEntry(account) { Tag = ++tradesCounter }; account.Trades.Add(entry); this.m_trades.Items.Add(entry); }
private static bool AddToTradeQueue(this SocketCommandContext Context, PK8 pk8, int code, string trainerName, bool sudo, PokeRoutineType type, PokeTradeType t, out string msg) { var user = Context.User; var userID = user.Id; var name = user.Username; var priority = user.EvaluatePriority(); var trainer = new PokeTradeTrainerInfo(trainerName); var notifier = new DiscordTradeNotifier <PK8>(pk8, trainer, code, Context); var detail = new PokeTradeDetail <PK8>(pk8, trainer, notifier, t, code: code); var trade = new TradeEntry <PK8>(detail, userID, type, name); var hub = SysCordInstance.Self.Hub; var Info = hub.Queues.Info; var added = Info.AddToTradeQueue(trade, userID, priority, sudo); if (added == QueueResultAdd.AlreadyInQueue) { msg = "Sorry, you are already in the queue."; return(false); } user.Timestamp(); var position = Info.CheckPosition(userID, type); var ticketID = ""; if (TradeStartModule.IsStartChannel(Context.Channel.Id)) { ticketID = $", unique ID: {detail.ID}"; } msg = $"{user.Mention} - Added to the {type} queue{ticketID}. Current Position: {position.Position}"; var botct = Info.Hub.Bots.Count; if (position.Position > botct) { var eta = Info.Hub.Config.Queues.EstimateDelay(position.Position, botct); msg += $". Estimated: {eta:F1} minutes."; } return(true); }
public void Set <T>(dynamic tpe) { { switch (typeof(T).Name) { case "TradeEntry": TradeEntry trd = tpe; var tpeU = context.tradeEntry.FirstOrDefault(trdE => trdE.id == trd.id); if (tpeU == null) { trd.id = Guid.NewGuid().ToString(); fixBadDate(ref trd); context.tradeEntry.Add(trd); } tpeU = trd; break; case "Trade": Trade trd_a = tpe; var tpeU2 = context.trade.FirstOrDefault(trd2 => trd2.id == trd_a.id); if (tpeU2 == null) { trd_a.guid = Guid.NewGuid().ToString(); context.trade.Add(trd_a); } tpeU2 = trd_a; break; case "InstrumentPerformance": InstrumentPerformance trd_b = tpe; var tpeU3 = context.instrumentPerformance.FirstOrDefault(trd3 => trd3.id == trd_b.id); if (tpeU3 == null) { trd_b.id = Guid.NewGuid().ToString(); context.instrumentPerformance.Add(trd_b); } tpeU3 = trd_b; break; default: break; } context.SaveChanges(); } }
internal TradeData(TradeEntry entry) { if (entry == null) throw new ArgumentNullException(nameof(entry)); this.Tag = entry.Tag != null ? entry.Tag.ToString() : string.Empty; this.Type = TradeTypeFromTradeRecordType(entry.Type); this.Side = entry.Side; this.Symbol = entry.Symbol; this.Price = entry.Price; this.Volume = entry.Volume; this.Commission = entry.Commission; this.AgentCommission = entry.AgentCommission; this.Swap = entry.Swap; //this.Rate = entry.StaticMarginRate; this.ProfitStatus = entry.ProfitStatus; this.MarginStatus = entry.MarginStatus; this.Profit = entry.Profit; this.Margin = entry.Margin; }
protected TradingResult OnTradeResult(AccountInfo account, Ticker ticker, byte[] data) { if (data == null) { return(null); } string text = Encoding.UTF8.GetString(data); JObject res = JsonConvert.DeserializeObject <JObject>(text); if (res.Value <string>("code") != null) { LogManager.Default.Error(this, "trade", text); return(null); } TradingResult tr = new TradingResult(); tr.OrderId = res.Value <string>("orderId"); tr.Amount = Convert.ToDouble(res.Value <string>("executedQty")); tr.Value = Convert.ToDouble(res.Value <string>("price")); tr.Total = tr.Amount * tr.Value; tr.OrderStatus = res.Value <string>("status"); tr.Filled = tr.OrderStatus == "FILLED"; JArray fills = res.Value <JArray>("fills"); if (fills == null) { return(tr); } foreach (JObject item in fills) { TradeEntry e = new TradeEntry(); e.Amount = Convert.ToDouble(item.Value <string>("qty")); e.Rate = Convert.ToDouble(item.Value <string>("price")); e.Fee = Convert.ToDouble(item.Value <string>("comission")); e.FeeAsset = item.Value <string>("commissionAsset"); tr.Trades.Add(e); } return(tr); }
private bool AddToTradeQueue(PK8 pk8, int code, OnWhisperReceivedArgs e, bool sudo, PokeRoutineType type, out string msg) { // var user = e.WhisperMessage.UserId; var userID = ulong.Parse(e.WhisperMessage.UserId); var name = e.WhisperMessage.DisplayName; var trainer = new PokeTradeTrainerInfo(name); var notifier = new TwitchTradeNotifier <PK8>(pk8, trainer, code, e.WhisperMessage.Username, client, Channel); var detail = type == PokeRoutineType.DuduBot ? new PokeTradeDetail <PK8>(pk8, trainer, notifier, PokeTradeType.Dudu, code: code) : new PokeTradeDetail <PK8>(pk8, trainer, notifier, PokeTradeType.Specific, code: code); var trade = new TradeEntry <PK8>(detail, userID, type, name); var added = Info.AddToTradeQueue(trade, userID, sudo); if (added == QueueResultAdd.AlreadyInQueue) { msg = "Sorry, you are already in the queue."; return(false); } msg = $"Added {name} to the queue. Your current position is: {Info.CheckPosition(userID, type).Position}"; return(true); }
internal TradeEntry CreateEntry(AccountEntry owner) { var result = new TradeEntry(owner) { Tag = this.Tag, Type = TradeRecordTypeFromTradeType(this.Type), Side = this.Side, Symbol = this.Symbol, Price = this.Price, Volume = this.Volume, Commission = this.Commission, AgentCommission = this.AgentCommission, Swap = this.Swap, //StaticMarginRate = this.Rate, ProfitStatus = this.ProfitStatus, MarginStatus = this.MarginStatus, Profit = this.Profit, Margin = this.Margin }; return result; }
public void OnTradeComplete(Mobile m, TradeEntry entry) { bool distCheck = entry.Distance > 0; // 0 distance indicates they used a moongate if (m is PlayerMobile pm && distCheck) { if (!CompleteTable.ContainsKey(pm)) { CompleteTable[pm] = 1; } else { CompleteTable[pm]++; } } if (TotalTradesComplete > MinComplete || distCheck) { TotalTradesComplete++; } }
private bool AddToTradeQueue(PK8 pk8, int code, string trainerName, bool sudo, PokeRoutineType type, out string msg) { var user = Context.User; var userID = user.Id; var name = user.Username; var trainer = new PokeTradeTrainerInfo(trainerName); var notifier = new DiscordTradeNotifier <PK8>(pk8, trainer, code, Context); var detail = new PokeTradeDetail <PK8>(pk8, trainer, notifier, PokeTradeType.Dudu, code: code); var trade = new TradeEntry <PK8>(detail, userID, type, name); var added = Info.AddToTradeQueue(trade, userID, sudo); if (added == QueueResultAdd.AlreadyInQueue) { msg = "Sorry, you are already in the queue."; return(false); } msg = $"Added {user.Mention} to the queue for trade type: {type}. Your current position is: {Info.CheckPosition(userID, type).Position}"; return(true); }
private async void loopTrades(ulong toAdd = ulong.MaxValue) { var trainerDetail = "Berichan" + (toAdd == ulong.MaxValue ? "" : toAdd.ToString()); var userID = toAdd == ulong.MaxValue ? 0ul : toAdd; var trainer = new PokeTradeTrainerInfo(trainerDetail); var pk = new PK8(); while (true) { if (!Hub.Queues.GetQueue(PokeRoutineType.SeedCheck).Contains(trainerDetail)) { await Task.Delay(100).ConfigureAwait(false); var notifier = new WebTradeNotifier <PK8>(pk, trainer, Code, WebNotifierInstance); var detail = new PokeTradeDetail <PK8>(pk, trainer, notifier, PokeTradeType.Seed, Code, true); var trade = new TradeEntry <PK8>(detail, userID, PokeRoutineType.SeedCheck, ""); Info.AddToTradeQueue(trade, userID, false); } await Task.Delay(1_000).ConfigureAwait(false); } }
internal TradeEntry CreateEntry(AccountEntry owner) { var result = new TradeEntry(owner) { Tag = this.Tag, Type = TradeRecordTypeFromTradeType(this.Type), Side = this.Side, Symbol = this.Symbol, Volume = this.Volume, MaxVisibleVolume = this.MaxVisibleVolume, Price = this.Price, StopPrice = this.StopPrice, Commission = this.Commission, AgentCommission = this.AgentCommission, Swap = this.Swap, //StaticMarginRate = this.Rate, ProfitStatus = this.ProfitStatus, MarginStatus = this.MarginStatus, Profit = this.Profit, Margin = this.Margin }; return(result); }
public static IOrderModel ToCalculatorOrder(TradeEntry trade) { return(new CalculatorOrder(trade)); }
public static ICalculatorOrder ToCalculatorOrder(TradeEntry trade) { return new CalculatorOrder(trade); }
public static void OnTradeComplete(Mobile from, TradeEntry entry) { var dest = GetCityInstance(entry.Destination); var origin = GetCityInstance(entry.Origin); int gold = entry.CalculateGold(); origin.AddToTreasury(from, gold); from.SendLocalizedMessage(1154761, String.Format("{0}\t{1}", gold.ToString("N0", CultureInfo.GetCultureInfo("en-US")), origin.Definition.Name)); // ~1_val~ gold has been deposited into the ~2_NAME~ City treasury for your efforts! origin.AwardLove(from, 150); dest.AwardLove(from, 150); origin.CompletedTrades++; }
void OnAddTrade(object sender, EventArgs e) { var account = this.GetCurrentAccountEntry(); if (account == null) return; var entry = new TradeEntry(account) { Tag = ++tradesCounter }; account.Trades.Add(entry); this.m_trades.Items.Add(entry); }
void PrepareCalculator(AccountInfo accountUpdate, IEnumerable<SymbolInfo> symbolsUpdate, IDictionary<string, Quote> quotesUpdate) { if (accountUpdate != null) { this.account.Balance = accountUpdate.Balance; this.account.Currency = accountUpdate.Currency; this.account.Type = accountUpdate.Type; if (this.account.Type != AccountType.Cash) { this.account.Leverage = accountUpdate.Leverage; var provider = new SymbolInfoFeaturesProvider(); var features = provider.GetInfo(new FixProtocolVersion(this.feed.UsedProtocolVersion)); if (features.IsCurrencyPrecisionSupported && this.feed.Cache.Currencies.Select(o => o.Name).Contains(account.Currency)) { var precisionProvider = new CurrencyPrecisionProvider(this.feed.Cache.Currencies); this.account.RoundingService = new AccountRoundingService(FinancialRounding.Instance, precisionProvider, account.Currency); } } } if (this.account.Type != AccountType.Cash) { this.account.Balance = this.trade.Cache.AccountInfo.Balance; } if (symbolsUpdate != null) { this.calculator.Symbols.Clear(); var provider = new SymbolInfoFeaturesProvider(); var features = provider.GetInfo(new FixProtocolVersion(this.feed.UsedProtocolVersion)); foreach (var symbol in symbolsUpdate.OrderByDescending(o => o.Name)) { var entry = new SymbolEntry(this.calculator, symbol.Name, symbol.SettlementCurrency, symbol.Currency) { MarginFactor = symbol.GetMarginFactor(), MarginFactorOfPositions = 1, MarginFactorOfLimitOrders = 1, MarginFactorOfStopOrders = 1, Hedging = symbol.MarginHedge, MarginCalcMode = symbol.MarginCalcMode, }; if (features.IsGroupSortOrderSupported) entry.GroupSortOrder = symbol.GroupSortOrder; if (features.IsSortOrderSupported) entry.SortOrder = symbol.SortOrder; this.calculator.Symbols.Add(entry); } if (features.IsCurrencyPrecisionSupported && this.feed.Cache.Currencies.Select(o => o.Name).Contains(account.Currency)) { var precisionProvider = new CurrencyPrecisionProvider(this.feed.Cache.Currencies); this.account.RoundingService = new AccountRoundingService(FinancialRounding.Instance, precisionProvider, account.Currency); } var currencies = features.IsCurrencySortOrderSupported ? this.feed.Cache.Currencies.OrderBy(o => o.SortOrder).Select(o => o.Name) : MajorCurrencies; this.calculator.Currencies.Clear(); foreach (var currency in currencies) { this.calculator.Currencies.Add(currency); } } foreach (var quote in quotesUpdate.Values) { this.calculator.Prices.Update(quote.Symbol, quote.Bid, quote.Ask); this.calculatorQuotes[quote.Symbol] = quote; } this.account.Trades.Clear(); var records = this.trade.Cache.TradeRecords; foreach (var record in records) { var entry = new TradeEntry(this.account, record.Type, record.Side, record.Symbol, record.Price, record.Volume) { Tag = record, Commission = record.Commission, AgentCommission = record.AgentCommission, Swap = record.Swap, }; this.account.Trades.Add(entry); } var positions = this.trade.Cache.Positions; foreach (var position in positions) { var buy = new TradeEntry(this.account, TradeRecordType.Position, TradeRecordSide.Buy, position.Symbol, position.BuyPrice.Value, position.BuyAmount) { Tag = position, Commission = position.Commission, AgentCommission = position.AgentCommission, Swap = position.Swap }; var sell = new TradeEntry(this.account, TradeRecordType.Position, TradeRecordSide.Sell, position.Symbol, position.SellPrice.Value, position.SellAmount) { Tag = position }; // some magic; see TryProcessAsPosition of StateInfo class this.account.Trades.Add(buy); this.account.Trades.Add(sell); } }
public static void OnSlimTradeComplete(Mobile from, TradeEntry entry) { var dest = GetCityInstance(entry.Destination); var origin = GetCityInstance(entry.Origin); origin.AwardHate(from, 25); dest.AwardHate(from, 25); }
public async Task <BotModel> Simulate(BotModel bot) { bot.TradeBook = new TradeBook() { Id = 10, TradeEntries = new List <TradeEntry>(1000), Series = new List <SeriesItem>(1000) }; // gather needed data to execute trades against var tickerDetails = await IntrinioService.GetTickerDetails(bot.TargetTicker.TickerSymbol); var prices = await IntrinioService.GetTickerPrices(bot.TargetTicker.TickerSymbol, bot.StartDate.AddDays(-1), DateTime.UtcNow.Date); var priceLookup = prices.ToDictionary(k => k.Date.ToString("yyyyMMddHHmmss"), m => new NormalizedPriceItem() { High = (int)(m.High * 100), Low = (int)(m.Low * 100), Open = (int)(m.Open * 100), Close = (int)(m.Close * 100), Date = DateTime.SpecifyKind(m.Date, DateTimeKind.Utc) }); // register data with the model so it can perform its analysis bot.Model.RegisterInputSources(IntrinioService.GetTickerPrices, bot.StartDate, DateTime.UtcNow); // run get signal over a time series of the target equity var idxDate = bot.StartDate; var stopDate = DateTime.UtcNow; var idxDateString = idxDate.ToString("yyyyMMddHHmmss"); // Take the first time step and use it to setup initial portfolio NormalizedPriceItem currPrice; while (!priceLookup.ContainsKey(idxDateString)) { idxDate = idxDate.AddDays(1); idxDateString = idxDate.ToString("yyyyMMddHHmmss"); } currPrice = priceLookup[idxDateString]; var prevItem = new SeriesItem() { Signal = Signal.Hold, Date = idxDate, Open = currPrice.Open, High = currPrice.High, Low = currPrice.Low, Close = currPrice.Close, PortfolioValue = currPrice.Close, Position = 0 }; bot.TradeBook.Series.Add(prevItem); idxDate = idxDate.AddDays(1); idxDateString = idxDate.ToString("yyyyMMddHHmmss"); while (idxDate < stopDate) { // make sure the date is included in our data set coming from the data provider (ie intrinio) // (ie skip weekends) if (priceLookup.ContainsKey(idxDateString)) { // set up calculations for this time-step var(newSignal, multiplier) = await bot.Model.GetSignal(idxDate); var tradeEntry = new TradeEntry() { Type = "pin", RollOverColor = blue }; currPrice = priceLookup[idxDateString]; var seriesItem = new SeriesItem() { Date = idxDate, Open = currPrice.Open, High = currPrice.High, Low = currPrice.Low, Close = currPrice.Close, Signal = newSignal, }; /// /// ==================================================================== /// Determine if we want to alter our position based on the model signal /// ==================================================================== /// var positionChange = 0; if (prevItem.Signal != newSignal) { switch (newSignal) { case Signal.Buy: // if prev position is a short we want to reverse it positionChange = (int)Math.Round(bot.OrderAmount * multiplier) - prevItem.Position; tradeEntry.Position = TradeType.Buy; tradeEntry.Text = "B"; tradeEntry.Date = idxDate; tradeEntry.Price = seriesItem.Close; seriesItem.Position = positionChange + prevItem.Position; tradeEntry.Description = Math.Abs(positionChange) + " share(s) purchased @ $" + seriesItem.Close / 100.0; tradeEntry.BackgroundColor = buyColor; break; case Signal.Sell: // if long the prev position we want to reverse it positionChange = -1 * (int)Math.Round(bot.OrderAmount * multiplier) - prevItem.Position; tradeEntry.Position = TradeType.Sell; tradeEntry.Text = "S"; tradeEntry.Date = idxDate; tradeEntry.Price = seriesItem.Close; seriesItem.Position = positionChange + prevItem.Position; tradeEntry.Description = Math.Abs(positionChange) + " share(s) sold @ $" + seriesItem.Close / 100.0; tradeEntry.BackgroundColor = sellColor; break; case Signal.Hold: // if long the prev position we want to reverse it positionChange = -1 * prevItem.Position; tradeEntry.Text = "H"; tradeEntry.Date = idxDate; tradeEntry.Price = seriesItem.Close; seriesItem.Position = positionChange + prevItem.Position; if (positionChange > 0) { tradeEntry.Description = Math.Abs(positionChange) + " share(s) bought @ $" + seriesItem.Close / 100.0 + " to flatten position."; tradeEntry.Position = TradeType.Buy; } else { tradeEntry.Description = Math.Abs(positionChange) + " share(s) sold @ $" + seriesItem.Close / 100.0 + " to flatten position."; tradeEntry.Position = TradeType.Sell; } tradeEntry.BackgroundColor = "#0075be"; break; default: throw new Exception("Unhandled signal '" + newSignal.ToString() + "'!!!"); } bot.TradeBook.TradeEntries.Add(tradeEntry); } else { seriesItem.Position = prevItem.Position; } /// /// ==================================================================== /// /// /// ==================================================================== /// Calculate portfolio value /// Use the previous indexes signal value / position and the current closed value /// to determine how the porfolio changed /// ==================================================================== /// if (prevItem.Position != 0) { seriesItem.PortfolioValue = prevItem.Position * (seriesItem.Close - prevItem.Close) + prevItem.PortfolioValue; } else if (prevItem.Position < 0) { seriesItem.PortfolioValue = prevItem.Position * (seriesItem.Close - prevItem.Close) + prevItem.PortfolioValue; } else { seriesItem.PortfolioValue = prevItem.PortfolioValue; } /// /// ==================================================================== /// prevItem = seriesItem; bot.TradeBook.Series.Add(seriesItem); } idxDate = idxDate.AddDays(1); idxDateString = idxDate.ToString("yyyyMMddHHmmss"); } /// /// If we have an open position then lets go ahead and close it out /// if (prevItem.Position != 0) { var closeOutTradeEntry = new TradeEntry(); var positionChange = -1 * prevItem.Position; closeOutTradeEntry.Text = "H"; closeOutTradeEntry.Date = prevItem.Date; closeOutTradeEntry.Price = prevItem.Close; prevItem.Position = positionChange + prevItem.Position; if (positionChange > 0) { closeOutTradeEntry.Description = Math.Abs(positionChange) + " share(s) bought @ $" + prevItem.Close / 100.0 + " to flatten position."; } else { closeOutTradeEntry.Description = Math.Abs(positionChange) + " share(s) sold @ $" + prevItem.Close / 100.0 + " to flatten position."; } closeOutTradeEntry.BackgroundColor = "#0075be"; bot.TradeBook.TradeEntries.Add(closeOutTradeEntry); } /// /// ==================================================================== /// Calculate stats /// ==================================================================== /// var stats = new TradingStats(); var startingValue = bot.TradeBook.Series.First().PortfolioValue; var endingValue = bot.TradeBook.Series.Last().PortfolioValue; stats.TotalPnL = endingValue - startingValue; var tradeProfits = new List <int>(); for (int idx = 0; idx < bot.TradeBook.TradeEntries.Count - 1; idx += 2) { var entryTrade = bot.TradeBook.TradeEntries[idx]; var exitTrade = bot.TradeBook.TradeEntries[idx + 1]; //think more about this need to get true profit if (entryTrade.Position == TradeType.Buy) { tradeProfits.Add(exitTrade.Price - entryTrade.Price); } else { tradeProfits.Add(entryTrade.Price - exitTrade.Price); } } stats.WinPct = 100 * tradeProfits.Count(k => k > 0) / tradeProfits.Count(); bot.TradeBook.TradingStats = stats; bot.Model.Reset(); return(bot); }
public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int v = reader.ReadInt(); Owner = reader.ReadMobile(); Expires = reader.ReadDateTime(); Entry = new TradeEntry(reader); }
private void createTradeEntryToolStripMenuItem_Click(object sender, EventArgs e) { TradeEntry td = new TradeEntry(); td.ShowDialog(); }
private static bool AddToTradeQueue(this SocketCommandContext Context, PK8 pk8, int code, string trainerName, RequestSignificance sig, PokeRoutineType type, PokeTradeType t, SocketUser trader, out string msg, string requestedIgn = "") { var user = trader; var userID = user.Id; var name = user.Username; var trainer = new PokeTradeTrainerInfo(trainerName); var notifier = new DiscordTradeNotifier <PK8>(pk8, trainer, code, Context, user); var detail = new PokeTradeDetail <PK8>(pk8, trainer, notifier, t, code, userID, sig == RequestSignificance.Favored, requestedIgn); var trade = new TradeEntry <PK8>(detail, userID, type, name); var hub = SysCordInstance.Self.Hub; var Info = hub.Queues.Info; var added = Info.AddToTradeQueue(trade, userID, sig == RequestSignificance.Favored); if (added == QueueResultAdd.AlreadyInQueue) { msg = "Sorry, you are already in the queue."; return(false); } var position = Info.CheckPosition(userID, type); var ticketID = ""; if (TradeStartModule.IsStartChannel(Context.Channel.Id)) { ticketID = $", unique ID: {detail.ID}"; } var pokeName = ""; if (t == PokeTradeType.LanTrade || t == PokeTradeType.Specific || t == PokeTradeType.EggRoll && Info.Hub.Config.Discord.DisplayPokeName && pk8.Species != 0) { pokeName = $" Receiving: {(t == PokeTradeType.EggRoll ? "Mysterious Egg" : hub.Config.Trade.ItemMuleSpecies == (Species)pk8.Species && pk8.HeldItem != 0 ? $"{(Species)pk8.Species + " (" + ShowdownSet.GetShowdownText(pk8).Split('@', '\n')[1].Trim() + ")"}" : $"{(Species)pk8.Species}")}{(pk8.IsEgg && t != PokeTradeType.EggRoll ? " (Egg)" : "")}."; } if (t == PokeTradeType.LanRoll && Info.Hub.Config.Discord.DisplayPokeName && pk8.Species != 0) { pokeName = $" Receiving: An Illegal Egg."; } string overallPosition = ""; if (Info.Hub.Config.Discord.PostOverallQueueCount) { if (position.QueueCount != position.OverallQueueCount) { if (type == PokeRoutineType.SeedCheck && hub.Config.Queues.FlexMode == FlexYieldMode.LessCheatyFirst) { overallPosition = $" | __Overall: {position.Position}/{position.OverallQueueCount}__"; } else { overallPosition = $" | __Overall: {position.OverallPosition}/{position.OverallQueueCount}__"; } } else { overallPosition = $""; } } var ignName = ""; if (t == PokeTradeType.LanTrade || t == PokeTradeType.LanRoll) { if (requestedIgn != string.Empty) { ignName = $" Looking for {requestedIgn}."; } } msg = $"{user.Mention} - Added to the **{type}** queue{ticketID}. Current Position: __{type}: {position.Position}/{position.QueueCount}__{overallPosition}.{pokeName}{ignName}"; var botct = Info.Hub.Bots.Count; if (position.Position > botct) { var eta = Info.Hub.Config.Queues.EstimateDelay(position.Position, botct); msg += $" Estimated: {eta:F1} minutes."; } return(true); }