示例#1
0
        public async Task <CoinData> GetCoinDetailAsync(string id)
        {
            try
            {
                CoinData coinDetail = await Policy.Handle <HttpRequestException>(exception =>
                {
                    Console.WriteLine($"API Exception when connection to Coin Gecko API: {exception.Message}");
                    return(true);
                })
                                      .WaitAndRetryAsync(retryCount: 3,
                                                         sleepDurationProvider: retryAttempt =>
                                                         TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                                                         onRetry: (ex, time) =>
                {
                    Console.WriteLine($"Retry exception: {ex.Message}, retrying...");
                })
                                      .ExecuteAsync(async() => await _coinGeckoApi.GetCoinData(id));

                return(coinDetail);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Unable to get data from server: {ex.Message}");
                throw;
            }
        }
示例#2
0
 private string BuildLatestBlockFieldText(CoinData data)
 {
     return($"***Hash***: {data.TopBlockHash}\n" +
            $"***Height***: {data.BlockHeight - 1}\n" +
            $"***Reward***: {data.BlockReward} {this._options.CoinCode}\n" +
            $"***Created***: {(DateTimeOffset.UtcNow - data.LastBlockTime).Value.ToDisplayString()} ago");
 }
示例#3
0
        /// <summary>Return the average value of this coin across the given exchanges</summary>
        public static Unit <decimal> AverageValue(this CoinData cd, IEnumerable <Exchange> source_exchanges)
        {
            // Find the average price on the available exchanges
            var value = new Average <decimal>();

            foreach (var exch in source_exchanges)
            {
                // If the exchange doesn't have this coin, skip it
                var coin = exch.Coins[cd.Symbol];
                if (coin == null)
                {
                    continue;
                }

                // If the exchange doesn't know the value of this coin yet, skip it
                var val = coin.ValueOf(1m);
                if (val == 0)
                {
                    continue;
                }

                // Add the value to the average
                value.Add(val);
            }

            // Return the average value
            return(value.Count != 0
                                ? value.Mean._(SettingsData.Settings.ValuationCurrency)
                                : cd.AssignedValue._(SettingsData.Settings.ValuationCurrency));
        }
示例#4
0
 //Robs coin generation(Not used)
 public CoinData CoinsJoin()
 {
     if (characters.Count > 0)
     {
         string coinsCollection = coin.Pop();
         // if there is a registered player
         if (coinDisplay.Count > 0)
         {
             CoinData newCoin = coinDisplay.Dequeue();
             newCoin.imageName = coinsCollection;
             newCoin.coinPos   = new Position
             {
                 X = new Random().Next(700),
                 Y = new Random().Next(500)
             };
             // Tell all the other clients that this player has Joined
             Clients.Others.coinJoined(newCoin);
             // Tell this client about all the other current
             Clients.Caller.clientCoins(coins);
             // Finaly add the new player on teh server
             coins.Add(newCoin);
             return(newCoin);
         }
     }
     return(null);
 }
示例#5
0
            /// <summary>
            /// returns a new <see cref="PropertyRow"/> corresponding to <paramref name="coinListing"/>.
            /// </summary>
            /// <param name="coinListing"></param>
            /// <returns>
            /// <see cref="PropertyRow"/> corresponding to <paramref name="coinListing"/>
            /// </returns>
            private PropertyRow getPropertyRow(CoinListing coinListing)
            {
                // convert coinListing to a CoinData to get a CoinData type object
                CoinData coinData = new CoinData(coinListing);

                return(new PropertyRow(coinData, PROPERTIES));
            }
示例#6
0
            /// <summary>
            /// returns a new <see cref="PropertyRow"/> constructed from <paramref name="coinTicker"/>.
            /// </summary>
            /// <param name="coinTicker"></param>
            /// <returns>
            /// new <see cref="PropertyRow"/> constructed from <paramref name="coinTicker"/>
            /// </returns>
            private PropertyRow getPropertyRow(CoinTicker coinTicker)
            {
                // construct row property list

                // merge coin data properties with coin ticker properties
                Property[] rowProperties = CollectionUtils.MergeToArray(
                    COIN_DATA_PROPERTIES,
                    coinTickerProperties);


                // construct row object list
                // get coin data object array
                CoinData coinData = new CoinData(coinTicker);

                CoinData[] coinDataObjectArray = CollectionUtils.DuplicateToArray(
                    coinData,
                    COIN_DATA_PROPERTIES.Length);

                // get coin ticker object array
                CoinTicker[] coinTickerObjectArray = CollectionUtils.DuplicateToArray(
                    coinTicker,
                    coinTickerProperties.Length);

                // merge coin data object array with coin ticker object array
                object[] rowObjects = CollectionUtils.MergeToArray(coinDataObjectArray, coinTickerObjectArray);

                // construct property row
                return(new PropertyRow(rowObjects, rowProperties));
            }
示例#7
0
 /// <summary>Notify that the main fund balance has changed</summary>
 private void Invalidate()
 {
     m_funds[0].NotifyPropertyChanged(nameof(Balance.Total));
     m_funds[0].NotifyPropertyChanged(nameof(Balance.Available));
     m_funds[0].NotifyPropertyChanged(nameof(Balance.Held));
     CoinData.NotifyBalanceChanged(Coin);
 }
示例#8
0
        /// <summary>Get/Set spot price (in Quote/Base)</summary>
        public Unit <decimal>?this[ETradeType tt]
        {
            get
            {
                return
                    (tt == ETradeType.Q2B ? m_spot_q2b :
                     tt == ETradeType.B2Q ? m_spot_b2q :
                     throw new Exception("Unknown trade type"));
            }
            set
            {
                if (value < 0m._(RateUnits))
                {
                    throw new Exception("Invalid spot price");
                }

                switch (tt)
                {
                default: throw new Exception("Unknown trade type");

                case ETradeType.Q2B: m_spot_q2b = value; break;

                case ETradeType.B2Q: m_spot_b2q = value; break;
                }

                CoinData.NotifyLivePriceChanged(Base);
                CoinData.NotifyLivePriceChanged(Quote);
            }
        }
示例#9
0
 public Coin(Game game, CoinData cData, Texture2D imageTexture, Point pos) : base(game)
 {
     Coindata = cData;
     game.Components.Add(this);
     Image        = imageTexture;
     Position     = pos;
     BoundingRect = new Rectangle((int)Position.X, Position.Y, Image.Width, Image.Height);
 }
示例#10
0
 private void OnCoinArrivedToPlayerEvent(GamePlayer player, CoinData objectGrabbed)
 {
     if (player != this)
     {
         return;
     }
     GiveCoins(1);
 }
示例#11
0
 private string BuildNetworkFieldText(CoinData data)
 {
     return($"***Hashrate***: {BuildHashrateString(data.Hashrate)}/s\n" +
            $"***Difficulty***: {data.Difficulty.ToString("N0", CultureInfo.InvariantCulture)}\n" +
            $"***Block Height***: {data.BlockHeight}\n" +
            $"***Transactions***: {data.TransactionsCount.ToString("N0", CultureInfo.InvariantCulture)}\n" +
            $"***Block Time***: {data.TargetBlockTime}sec");
 }
示例#12
0
        public async Task CoinSymbolShouldBeCorrect()
        {
            CoinData coinData = new CoinData();

            coinData = await _coinGeckoApiManager.GetCoinDetailAsync("0-5x-long-algorand-token");

            coinData.Symbol.Should().Be("algohalf");
        }
示例#13
0
        public void UpdateCoinMarketPrice(string coinName, decimal marketPrice)
        {
            CoinData coin = Coins.Find(x => x.Name == coinName);

            if (coin != null)
            {
                coin.MarketPrice = Math.Round(marketPrice, 2);
            }
        }
示例#14
0
    public static void SavePlayer(Player pl)
    {
        BinaryFormatter bF   = new BinaryFormatter();
        string          path = Application.persistentDataPath + "/coins.wave";
        FileStream      fS   = new FileStream(path, FileMode.Create);
        CoinData        sD   = new CoinData(pl);

        bF.Serialize(fS, sD);
    }
示例#15
0
 public CoinRepository(ICoinGeckoClient coinGeckoClient, IMemoryCache memoryCache, ICoinLogger coinLogger)
 {
     coinLogger.Log($"Initializing {nameof(CoinRepository)}.");
     _coinGeckoClient    = coinGeckoClient;
     _memoryCache        = memoryCache;
     _coinLogger         = coinLogger;
     _coins              = CoinData.GetAllCoins().Where(x => x.MarketCapRank > 0).GroupBy(x => x.Symbol).Select(x => x.OrderBy(y => y.MarketCapRank).First()).ToList();
     _coinBySymbolLookup = _coins.ToDictionary(x => x.Symbol, x => x);
 }
示例#16
0
        public void UpdateCoinBalance(string coinName, decimal balance)
        {
            CoinData coin = Coins.Find(x => x.Name == coinName);

            if (coin != null)
            {
                coin.Balance = Math.Round(balance, 4);
            }
        }
示例#17
0
        /// <summary>Reset the Sim Exchange</summary>
        public void Reset()
        {
            // Use the same random numbers for each run
            m_rng = new Random(54281);

            // Reset orders
            m_ord.Clear();
            Orders.Clear();
            m_order_id = 0;

            // Reset history
            m_his.Clear();
            History.Clear();
            m_history_id = 0;

            // Reset the balances to the initial values
            m_bal.Clear();
            Balance.Clear();
            Transfers.Clear();
            var exch_data = SettingsData.Settings.BackTesting.AccountBalances[Exchange.Name];

            foreach (var coin in Coins)
            {
                var bal = exch_data[coin.Symbol];
                m_bal.Add(coin, new AccountBalance(coin, bal.Total._(coin)));
                Balance.Add(new Balances(coin, bal.Total._(coin), Sim.Clock));

                // Add a "deposit" for each non-zero balance
                if (bal.Total != 0)
                {
                    Transfers.AddOrUpdate(new Transfer($"{bal.Symbol}-BackTesting", ETransfer.Deposit, coin, bal.Total._(coin), Model.UtcNow, Transfer.EStatus.Complete));
                }

                CoinData.NotifyBalanceChanged(coin);
            }

            // Reset the spot price and order books of the pairs
            m_depth.Clear();
            foreach (var pair in Pairs)
            {
                pair.SpotPrice[ETradeType.Q2B] = null;
                pair.SpotPrice[ETradeType.B2Q] = null;
                pair.MarketDepth.UpdateOrderBooks(new Offer[0], new Offer[0]);

                // Set the spot prices from the current candle at the simulation time
                var latest = PriceData[pair, Sim.TimeFrame]?.Current;
                if (latest != null)
                {
                    var spot_q2b = (decimal)latest.Close;
                    var spread   = spot_q2b * (decimal)m_spread_frac;
                    pair.SpotPrice[ETradeType.Q2B] = (spot_q2b)._(pair.RateUnits);
                    pair.SpotPrice[ETradeType.B2Q] = (spot_q2b - spread)._(pair.RateUnits);
                }
            }
        }
示例#18
0
    public static void SaveCoins(PlayerController player)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        string          path      = Application.persistentDataPath + "/coins.save";
        FileStream      stream    = new FileStream(path, FileMode.Create);

        CoinData data = new CoinData(player);

        formatter.Serialize(stream, data);
        stream.Close();
    }
示例#19
0
    public static CoinData LoadPlayer()
    {
        string path = Application.persistentDataPath + "/coins.wave";

        BinaryFormatter bF = new BinaryFormatter();
        FileStream      fS = new FileStream(path, FileMode.Open);
        CoinData        sD = bF.Deserialize(fS) as CoinData;

        fS.Close();
        return(sD);
    }
示例#20
0
        /// <summary>Implicitly create a new coin</summary>
        private Coin CreateCoin(string sym)
        {
            var coin = new Coin(sym, Exchange);

            if (!m_coin_data.Contains(coin.Meta))
            {
                m_coin_data.Add(coin.Meta);
            }

            CoinData.NotifyBalanceChanged(coin);
            return(coin);
        }
示例#21
0
        public async Task <CoinData> GetDataAsync(CancellationToken cancellationToken = default)
        {
            await this._coinLock.WaitAsync(cancellationToken).ConfigureAwait(false);

            try
            {
                // attempt to get cached first to avoid hammering APIs
                if (_cachedCoinData != null && DateTime.UtcNow < this._coinDateCacheTimeUTC + this._cachingOptions.CurrentValue.DataCacheLifetime)
                {
                    this._log.LogTrace("Found valid cached coin data, skipping APIs request");
                    return(_cachedCoinData);
                }

                this._log.LogInformation("Downloading all coin data");

                // start downloading
                Task <ExplorerNetworkData>  explorerNetworkTask  = this._explorerClient.GetNetworkDataAsync(cancellationToken);
                Task <ExplorerEmissionData> explorerEmissionTask = this._explorerClient.GetEmissionDataAsync(cancellationToken);
                Task <TxBitData>            txbitTask            = this._txbitClient.GetDataAsync(cancellationToken);
                // use explorer result to get last block data
                ExplorerNetworkData explorerNetworkData = await explorerNetworkTask.ConfigureAwait(false);

                Task <ExplorerBlockData> explorerBlockTask = this._explorerClient.GetBlockDataAsync(explorerNetworkData.TopBlockHash, cancellationToken);
                // await all remaining data
                TxBitData txbitData = await txbitTask.ConfigureAwait(false);

                ExplorerBlockData explorerBlockData = await explorerBlockTask.ConfigureAwait(false);

                ExplorerEmissionData explorerEmissionData = await explorerEmissionTask.ConfigureAwait(false);

                // aggregate all data and return
                this._cachedCoinData = new CoinData(txbitData.CurrencyName, txbitData.CurrencyCode)
                {
                    Supply            = explorerEmissionData.CirculatingSupply,
                    MarketCap         = txbitData.MarketCap,
                    BtcPrice          = txbitData.BidPrice,
                    BlockHeight       = explorerNetworkData.BlockHeight,
                    BlockReward       = explorerBlockData.Transactions.First(tx => tx.IsCoinbase).OutputsSum,
                    Difficulty        = explorerNetworkData.Difficulty,
                    Hashrate          = explorerNetworkData.Hashrate,
                    LastBlockTime     = explorerBlockData.Timestamp,
                    TargetBlockTime   = explorerNetworkData.TargetBlockTime,
                    TopBlockHash      = explorerBlockData.Hash,
                    TransactionsCount = explorerNetworkData.TransactionsCount
                };
                this._coinDateCacheTimeUTC = DateTime.UtcNow;
                return(this._cachedCoinData);
            }
            finally
            {
                try { this._coinLock.Release(); } catch { }
            }
        }
示例#22
0
        public async Task CoinDetailShouldBeCorrect()
        {
            CoinData coinData = new CoinData();

            coinData = await _coinGeckoApiManager.GetCoinDetailAsync("0-5x-long-algorand-token");

            coinData.Name.Should().Be("0.5X Long Algorand Token");
            coinData.Symbol.Should().Be("algohalf");
            coinData.image.Should().NotBeNull();
            coinData.description.Should().NotBeNull();
            coinData.market_data.current_price.usd.Should().BeGreaterOrEqualTo(0);
        }
示例#23
0
    public static void SaveCoin(CoinData coinData)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        string          path      = Path.Combine(Application.persistentDataPath, "coin.Thuong");

        FileStream stream = new FileStream(path, FileMode.Create);

        CoinCollected coinCollected = new CoinCollected(coinData);

        formatter.Serialize(stream, coinCollected);
        stream.Close();
    }
示例#24
0
        public Embed Build(CoinData data, IMessage message)
        {
            EmbedBuilder builder = this.CreateDefaultEmbed(message);

            builder.Title = this._options.CoinName;
            builder.Url   = this._options.CoinURL;
            builder.AddField("Current Supply", data.Supply.ToString("N0", CultureInfo.InvariantCulture), inline: true);
            builder.AddField("Market Cap", $"${data.MarketCap.ToString("0.00", CultureInfo.InvariantCulture)}", inline: true);
            builder.AddField("BTC Value", data.BtcPrice, inline: true);
            builder.AddField("Network", this.BuildNetworkFieldText(data), inline: false);
            builder.AddField("Last Block", this.BuildLatestBlockFieldText(data), inline: false);

            return(builder.Build());
        }
                /// <summary>
                /// returns <see cref="CoinData"/> section of <see cref="PortfolioEntryPropertyRow"/>
                /// <see cref="object"/> array.
                /// </summary>
                /// <seealso cref="CollectionUtils.DuplicateToArray{T}(T, int)"/>
                /// <param name="portfolioEntry"></param>
                /// <returns>
                /// <see cref="CoinData"/> section of <see cref="PortfolioEntryPropertyRow"/>
                /// <see cref="object"/> array.
                /// </returns>
                private static CoinData[] constructCoinDataArray(PortfolioEntry portfolioEntry)
                {
                    // get coin listing corresponding to PortfolioEntry coin id
                    CoinListing coinListing = CoinListingManager.Instance.GetCoinListing(portfolioEntry.CoinId);

                    // create a corresponding CoinData object
                    CoinData coinData = new CoinData(coinListing);

                    // construct CoinData array
                    CoinData[] coinDataArray = CollectionUtils.DuplicateToArray(
                        coinData,
                        COIN_DATA_PROPERTIES.Length);

                    return(coinDataArray);
                }
示例#26
0
        public void GenerateSitemapFile(string fileLocation)
        {
            Console.WriteLine($"Generating new sitemap file at '{fileLocation}'.");
            var coins   = CoinData.GetAllCoins();
            var sitemap = new Sitemap {
                UrlSet = coins.Select(x => new SitemapUrl(x)).ToList()
            };
            var serializer = new System.Xml.Serialization.XmlSerializer(typeof(Sitemap));

            using (var writer = new StreamWriter(fileLocation))
            {
                serializer.Serialize(writer, sitemap);
            }

            Console.WriteLine($"Completed generating new sitemap file at '{fileLocation}'.");
        }
示例#27
0
    void RefreshWithGlobalControls()
    {
        _player.transform.position = GlobalControl.Instance.playerData.currentPlayerPosition;

        for (int index = 0; index < GlobalControl.Instance.enemyData.Length; index++)
        {
            EnemyData  enemyData     = GlobalControl.Instance.enemyData [index];
            GameObject enemy         = enemies [index];
            Enemy      enemyBehavior = enemy.GetComponent <Enemy> ();

            // is a moving Enemy
            if (!enemyBehavior)
            {
                Transform childEnemy = enemy.transform.GetChild(0);
                enemyBehavior            = childEnemy.gameObject.GetComponent <Enemy> ();
                childEnemy.position      = enemyData.childPosition;
                enemy.transform.position = enemyData.currentPosition;
            }
            else
            {
                enemy.transform.position = enemyData.currentPosition;
            }

            if (enemyData.isStunned)
            {
                enemyBehavior.Stunned();
            }

            /*	if (enemyData.movingPlatformIndex >= 0) {
             *      SetObjectToChildOfPlatform (enemy, platforms [enemyData.movingPlatformIndex]);
             * } */
        }

        for (int index = 0; index < GlobalControl.Instance.coinData.Length; index++)
        {
            CoinData   coinData = GlobalControl.Instance.coinData [index];
            GameObject coin     = coins [index];
            coin.SetActive(coinData.doesExist);
        }

        for (int index = 0; index < GlobalControl.Instance.platformsData.Length; index++)
        {
            MovingPlatformData platformData = GlobalControl.Instance.platformsData [index];
            GameObject         platform     = platforms [index];
            platform.transform.position = platformData.currentPosition;
        }
    }
示例#28
0
    public void UpdateGlobalControls()
    {
        GlobalControl.Instance.playerData.movingPlatformIndex   = IndexOfMovingPlatform(_player);
        GlobalControl.Instance.playerData.currentPlayerPosition = _player.transform.position;

        for (int index = 0; index < enemies.Length; index++)
        {
            EnemyData  enemyData     = GlobalControl.Instance.enemyData [index];
            GameObject enemy         = enemies [index];
            Enemy      enemyBehavior = enemy.GetComponent <Enemy> ();

            // is a moving Enemy
            if (!enemyBehavior)
            {
                Transform childEnemy = enemy.transform.GetChild(0);
                enemyBehavior = childEnemy.gameObject.GetComponent <Enemy> ();

                enemyData.isStunned       = enemyBehavior.isStunned;
                enemyData.childPosition   = childEnemy.position;
                enemyData.currentPosition = enemy.transform.position;
                enemyData.isMovingEnemy   = true;
            }
            else
            {
                enemyData.isStunned       = enemyBehavior.isStunned;
                enemyData.currentPosition = enemy.transform.position;
                enemyData.isMovingEnemy   = false;
            }
        }

        for (int index = 0; index < coins.Length; index++)
        {
            CoinData   coinData = GlobalControl.Instance.coinData [index];
            GameObject coin     = coins [index];
            coinData.doesExist = coin.activeSelf;
        }

        for (int index = 0; index < platforms.Length; index++)
        {
            GameObject         platform     = platforms [index];
            MovingPlatformData platformData = GlobalControl.Instance.platformsData [index];
            platformData.currentPosition = platform.transform.position;

            PlatformMover platformMover = platform.GetComponent <PlatformMover> ();
            platformMover.myWaypointIndex = platformData.waypointIndex;
        }
    }
示例#29
0
        /// <summary>The sum of available balance across all exchanges</summary>
        public static Unit <decimal> NettAvailable(this CoinData cd, IEnumerable <Exchange> source_exchanges)
        {
            var avail = 0m;

            foreach (var exch in source_exchanges)
            {
                // If the exchange doesn't have this coin, skip it
                var coin = exch.Coins[cd.Symbol];
                if (coin == null)
                {
                    continue;
                }

                // Add the available balance to the total
                avail += coin.Balances.NettAvailable;
            }

            // Return the total available balance
            return(avail._(cd.Symbol));
        }
示例#30
0
    public static CoinData LoadCoins()
    {
        string path = Application.persistentDataPath + "/coins.save";

        if (File.Exists(path))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream      stream    = new FileStream(path, FileMode.Open);

            CoinData data = formatter.Deserialize(stream) as CoinData;
            stream.Close();

            return(data);
        }
        else
        {
            //Debug.Log("Save file not found in " + path);
            return(null);
        }
    }
示例#31
0
        private static CoinData Exchange(ulong n)
        {
            if (_data.ContainsKey(n))
                return _data[n];

            var coin1 = n / 2;
            var coin2 = n / 3;
            var coin3 = n / 4;
            var coinTotal = coin1 + coin2 + coin3;

            var profit = (n > coinTotal) ? 0 : (coinTotal - n);

            var data = new CoinData
            {
                Value = n,
                Profit = profit
            };

            var result = data + Exchange(coin1) + Exchange(coin2) + Exchange(coin3);
            _data[n] = result;
            return result;
        }