Ejemplo n.º 1
0
 void WriteBalanceSheet(BalanceSheet toDisplay)
 {
     scrollableBalanceSheet.text = "";
     scrollableBalanceSheet.text += "Period ending: " +  toDisplay.dateOfReport.month + " " + toDisplay.dateOfReport.year + " " + toDisplay.dateOfReport.day
         + " " + toDisplay.dateOfReport.dayOfTheMonth;
     scrollableBalanceSheet.text += "\n" + "\n" +"Cash at Bank: " + "$".PadLeft(100) + toDisplay.cashAtBank.ToString ();
     scrollableBalanceSheet.text += "\n" + "\n" +"Account Receivable: " + "$".PadLeft(89) + toDisplay.accountsReceivable.ToString ();
     scrollableBalanceSheet.text += "\n" + "\n" +"Inventories: " + "$".PadLeft(104) + toDisplay.inventories.ToString ();
     scrollableBalanceSheet.text += "\n" + "\n" +"Total Current Assets: " + "$".PadLeft(87) + toDisplay.totalCurrentAssets.ToString ();
     scrollableBalanceSheet.text += "\n" + "\n" +"Proprety and equipment: " + "$".PadLeft(81) + toDisplay.propretyAndEquipment.ToString ();
     scrollableBalanceSheet.text += "\n" + "\n" +"Total Assets: " + "$".PadLeft(101) + toDisplay.totalAssets.ToString ();
     scrollableBalanceSheet.text += "\n" + "\n" +"Account Payable: " + "$".PadLeft(93) + toDisplay.accountsPayable.ToString ();
     scrollableBalanceSheet.text += "\n" + "\n" +"Carbon Offset Receipt: " + "$".PadLeft(84) + toDisplay.carbonOffsetReceipts.ToString ();
     scrollableBalanceSheet.text += "\n" + "\n" +"Income Tax Payable: " + "$".PadLeft(87) + 	toDisplay.incomeTaxPayable.ToString ();
     scrollableBalanceSheet.text += "\n" + "\n" +"Divident Owed: " + "$".PadLeft(97) + toDisplay.dividendOwed.ToString ();
     scrollableBalanceSheet.text += "\n" + "\n" +"Current Maturity of Long Term Debt: " + "$".PadLeft(60) + toDisplay.currentMaturityofLongtermDebt.ToString ();
     scrollableBalanceSheet.text += "\n" + "\n" +"Total Current Liability: " + "$".PadLeft(85) + toDisplay.totalCurrentLiabilities.ToString ();
     scrollableBalanceSheet.text += "\n" + "\n" +"Long Term Debt: " + "$".PadLeft(95) + toDisplay.longTermDebt.ToString ();
     scrollableBalanceSheet.text += "\n" + "\n" +"Share Capital: " + "$".PadLeft(100) + toDisplay.shareCapital.ToString ();
     scrollableBalanceSheet.text += "\n" + "\n" +"Retained Erning: " + "$".PadLeft(96) + toDisplay.retainedEarnings.ToString ();
     scrollableBalanceSheet.text += "\n" + "\n" +"Owners Equity: " + "$".PadLeft(99) + toDisplay.ownersEquity.ToString ();
     scrollableBalanceSheet.text += "\n" + "\n" +"Total Liabilities and Owners Equity: " + "$".PadLeft(64) + toDisplay.totalLiabilitiesAndOwnersEquity.ToString ();
 }
Ejemplo n.º 2
0
 public void CurrentRatio_CorrectCalculation()
 {
     Assert.AreEqual(20f, BalanceSheet.CurrentRatio(5000, 100000));
 }
Ejemplo n.º 3
0
 public void DebtToIncomeRatio_CorrectCalculation()
 {
     Assert.AreEqual(0.2f, BalanceSheet.DebtToIncomeRatio(5000, 25000));
 }
Ejemplo n.º 4
0
        public void TestBalanceSheetWithTransactions()
        {
            ILoggerFactory loggerFactory = new LoggerFactory();

            using (var sqliteMemoryWrapper = new SqliteMemoryWrapper())
            {
                var currencyFactory   = new CurrencyFactory();
                var usdCurrencyEntity = currencyFactory.Create(CurrencyPrefab.Usd, true);
                currencyFactory.Add(sqliteMemoryWrapper.DbContext, usdCurrencyEntity);

                var accountFactory = new AccountFactory();
                Entities.Account incomeAccountEntity =
                    accountFactory.Create(AccountPrefab.Income, usdCurrencyEntity);
                Entities.Account checkingAccountEntity =
                    accountFactory.Create(AccountPrefab.Checking, usdCurrencyEntity);
                Entities.Account capitalAccountEntity =
                    accountFactory.Create(AccountPrefab.Capital, usdCurrencyEntity);
                Entities.Account rentExpenseAccountEntity =
                    accountFactory.Create(AccountPrefab.RentExpense, usdCurrencyEntity);
                Entities.Account creditCardAccountEntity =
                    accountFactory.Create(AccountPrefab.CreditCard, usdCurrencyEntity);

                accountFactory.Add(sqliteMemoryWrapper.DbContext, incomeAccountEntity);
                accountFactory.Add(sqliteMemoryWrapper.DbContext, checkingAccountEntity);
                accountFactory.Add(sqliteMemoryWrapper.DbContext, capitalAccountEntity);
                accountFactory.Add(sqliteMemoryWrapper.DbContext, rentExpenseAccountEntity);
                accountFactory.Add(sqliteMemoryWrapper.DbContext, creditCardAccountEntity);

                var transactions = new Entities.Transaction[]
                {
                    new Entities.Transaction
                    {
                        CreditAccount = capitalAccountEntity,
                        DebitAccount  = checkingAccountEntity,
                        Amount        = 100m,
                        At            = new DateTime(2018, 1, 1)
                    },// capital=100CR,checking=100DR
                    new Entities.Transaction
                    {
                        CreditAccount = creditCardAccountEntity,
                        DebitAccount  = rentExpenseAccountEntity,
                        Amount        = 40m,
                        At            = new DateTime(2018, 1, 2)
                    },// capital=100CR,checking=100DR,credit-card=40CR,rent=40DR
                    new Entities.Transaction
                    {
                        CreditAccount = checkingAccountEntity,
                        DebitAccount  = creditCardAccountEntity,
                        Amount        = 40m,
                        At            = new DateTime(2018, 1, 3)
                    },// capital=100CR,checking=60DR,rent=40DR
                    new Entities.Transaction
                    {
                        CreditAccount = incomeAccountEntity,
                        DebitAccount  = checkingAccountEntity,
                        Amount        = 200m,
                        At            = new DateTime(2018, 1, 4)
                    }// capital=100CR,checking=260DR,rent=40DR,income=200CR
                };
                sqliteMemoryWrapper.DbContext.Transactions.AddRange(transactions);
                sqliteMemoryWrapper.DbContext.SaveChanges();

                var accountService = new AccountService(
                    loggerFactory,
                    sqliteMemoryWrapper.DbContext
                    );
                var currencyService = new CurrencyService(
                    loggerFactory,
                    sqliteMemoryWrapper.DbContext
                    );
                var balanceSheetService = new BalanceSheetService(
                    loggerFactory,
                    sqliteMemoryWrapper.DbContext
                    );

                BalanceSheet            balanceSheetBeforeTransactions            = balanceSheetService.Generate(new DateTime(2017, 1, 1));
                List <BalanceSheetItem> balanceSheetBeforeTransactionsAssets      = balanceSheetBeforeTransactions.Assets.ToList();
                List <BalanceSheetItem> balanceSheetBeforeTransactionsLiabilities = balanceSheetBeforeTransactions.Liabilities.ToList();

                Assert.AreEqual(usdCurrencyEntity.Symbol, balanceSheetBeforeTransactions.CurrencySymbol);
                Assert.AreEqual(0, balanceSheetBeforeTransactions.TotalAssets);
                Assert.AreEqual(0, balanceSheetBeforeTransactions.TotalLiabilities);
                Assert.AreEqual(0, balanceSheetBeforeTransactions.NetWorth);
                Assert.AreEqual(0, balanceSheetBeforeTransactionsAssets.Count);
                Assert.AreEqual(0, balanceSheetBeforeTransactionsLiabilities.Count);

                BalanceSheet            balanceSheetTwoTransactions            = balanceSheetService.Generate(new DateTime(2018, 1, 2));
                List <BalanceSheetItem> balanceSheetTwoTransactionsAssets      = balanceSheetTwoTransactions.Assets.ToList();
                List <BalanceSheetItem> balanceSheetTwoTransactionsLiabilities = balanceSheetTwoTransactions.Liabilities.ToList();

                Assert.AreEqual(usdCurrencyEntity.Symbol, balanceSheetTwoTransactions.CurrencySymbol);
                Assert.AreEqual(100, balanceSheetTwoTransactions.TotalAssets);
                Assert.AreEqual(-40, balanceSheetTwoTransactions.TotalLiabilities);
                Assert.AreEqual(60, balanceSheetTwoTransactions.NetWorth);
                Assert.AreEqual(1, balanceSheetTwoTransactionsAssets.Count);
                Assert.AreEqual(1, balanceSheetTwoTransactionsLiabilities.Count);
                Assert.AreEqual(checkingAccountEntity.Name, balanceSheetTwoTransactionsAssets[0].Name);
                Assert.AreEqual(100, balanceSheetTwoTransactionsAssets[0].Balance);
                Assert.AreEqual(creditCardAccountEntity.Name, balanceSheetTwoTransactionsLiabilities[0].Name);
                Assert.AreEqual(-40, balanceSheetTwoTransactionsLiabilities[0].Balance);

                BalanceSheet            balanceSheetAtEnd            = balanceSheetService.Generate(new DateTime(2018, 2, 1));
                List <BalanceSheetItem> balanceSheetAtEndAssets      = balanceSheetAtEnd.Assets.ToList();
                List <BalanceSheetItem> balanceSheetAtEndLiabilities = balanceSheetAtEnd.Liabilities.ToList();

                Assert.AreEqual(usdCurrencyEntity.Symbol, balanceSheetAtEnd.CurrencySymbol);
                Assert.AreEqual(260, balanceSheetAtEnd.TotalAssets);
                Assert.AreEqual(0, balanceSheetAtEnd.TotalLiabilities);
                Assert.AreEqual(260, balanceSheetAtEnd.NetWorth);
                Assert.AreEqual(1, balanceSheetAtEndAssets.Count);
                Assert.AreEqual(1, balanceSheetAtEndLiabilities.Count);
                Assert.AreEqual(checkingAccountEntity.Name, balanceSheetAtEndAssets[0].Name);
                Assert.AreEqual(260, balanceSheetAtEndAssets[0].Balance);
                Assert.AreEqual(creditCardAccountEntity.Name, balanceSheetAtEndLiabilities[0].Name);
                Assert.AreEqual(0, balanceSheetAtEndLiabilities[0].Balance);
            }
        }
Ejemplo n.º 5
0
    //Runs (simulates) the reception desk for one month.
    public IEnumerator RunWeeklySimulation()
    {
        float staffCostMonthlyDP = 0;
        float staffCostMonthlyHS = 0;
        float staffCostMonthlyFB = 0;
        float staffCostMonthlyFD = 0;
        float staffCostMonthlyCF = 0;
        float staffCostMonthlyOT = 0;

        isSimulating = true;
        MasterReference.accountsPayable += bankingTab.GetLoanRepayments();
        MasterReference.accountsPayable += emsTab.GetMonthlyEMSCosts();
        MasterReference.accountsReceivable = 0f;

        //Monthly Report Creator.
        newMonthlyReport.numbDepartmentHead = Staff.staffDepartmentHead.Count;
        newMonthlyReport.numbHotelServicesStaff = Staff.staffHotelServices.Count;
        newMonthlyReport.numbFoodAndBeverageStaff = Staff.staffFoodAndBeverages.Count;
        newMonthlyReport.numbFrontDeskStaff = Staff.staffFrontDesk.Count;
        newMonthlyReport.numbConferenceStaff = Staff.staffConference.Count;
        newMonthlyReport.numbOtherStaff = Staff.staffOthers.Count;
        //-------------------------------------------//
        for (int weeks = 0; weeks < Calendar.GetNumberOfWeeksInMonth(); weeks++)
        {

            //Try and generate a random event each week.
            randomEvent.InitiateRandomEvent();
            //runs the stafftraining function to increase or decrease staff training.
            staffMenu.TrainStaff();
            //once a week degrade our special rooms.
            refurbishmentTab.DegradeSpecialRooms();
            //-------------------------------------------run day by day simulation---------------------------------------------------------//

            yield return new WaitForSeconds(debugDayDelay);
            //For each of the weekdays (Mon-Thurs inclusive) try to book rooms based on popularity vs cost
            WeekDays dayOfWeek;
            for (dayOfWeek = WeekDays.Monday; dayOfWeek <= WeekDays.Sunday; dayOfWeek++)
            {
                //set the date.
                Calendar.addDay();
                Days++;
                //Ticks the billboard duration by one.
                assetSwapper.TickDown();
                //Determine how many special groups will book.
                specialBookings specialBooked = SpecialBookingRun();
                //Determine how many rooms we will try to book:
                int roomsToBook = (int)((calendarController.seasonalTrends[Calendar.GetDayOfTheYear()]) *
                                        (MasterReference.ReturnRegularBookingPop() / 100f));

                //check if enought ppl show up to trigger overbooking.
                if((roomsToBook-specialBooked.numberOfRooms)/(BedroomBehaviour.allBedrooms.Count-specialBooked.numberOfRooms) > 0.9 && revenueManagementTab.GetOverbooked())
                {

                    roomsToBook += (roomsToBook/revenueManagementTab.GetOverbooking());

                    int overbookedCustomer = ((roomsToBook+specialBooked.numberOfRooms) - BedroomBehaviour.allBedrooms.Count);
                    if(overbookedCustomer > 0)
                    {
                        for(int i = 0; i < overbookedCustomer; i++)
                        {
                            feedbackController.TryGenFeedBack("OverBooked",70f);//70% chance an overbooked customer will complain.

                            MasterReference.accountsPayable += 300f;
                            MasterReference.hotelExposure--;
                        }
                    }
                }

                //Try to book specialgroups Rooms.---------------
                BedroomBehaviour.GetNumberOfRoomsAvailable();
                if(BedroomBehaviour.roomsAvailable > specialBooked.numberOfRooms && specialBooked.numberOfRooms != 0)
                {
                    //check for price ratio here.
                    if(CheckGroupCost(specialBooked))
                    {
                        //Debug.LogError("Special Group Booked for "+ specialBooked.numberOfDays + " Days for "+ specialBooked.numberOfRooms + "rooms for a "+ specialBooked.type);
                        for(int i = 0; i < specialBooked.numberOfRooms; i++)
                        BookRoomSpecial(dayOfWeek, specialBooked);
                    }
                    else
                    {
                        feedbackController.TryGenFeedBack("Expensive",30f);//30% chance customoer will complain for overpriced.
                    }
                }
                else if(specialBooked.numberOfRooms != 0)
                {
                    //need to provide feedback to the player that a group tryed to book rooms but hotel didn't have capacity.
                    feedbackController.TryGenFeedBack("Full",10f);//10% chance customer will complain due to full capacity.
                }

                //-----------------------------------------------
                float occupancyDiscount =  controller.transform.FindChild ("RevenueManagerCTR").gameObject.GetComponent<RevenueManagement>().discountOnOccupancy();

                //Try to book that many rooms:
                for (int j = 0; j < roomsToBook; j++)
                {
                    BedroomBehaviour.GetNumberOfRoomsAvailable ();
                    if (BedroomBehaviour.roomsAvailable > 0)
                    {
                        BookRoom (dayOfWeek, occupancyDiscount);
                    }
                    else
                    {
                        Debug.Log("no rooms");
                        feedbackController.TryGenFeedBack("Full",10f);//10% chance customer will complain due to full capacity.
                    }
                }
                //set the price for current occupancy
                BedroomBehaviour.occupancyDiscount = occupancyDiscount/100f;
                //Step the day counter for all rooms
                BedroomBehaviour.StepDay (dayOfWeek);
                float ProdReq = BedroomBehaviour.ProdRequired;
                float StaffProduction = staffMenu.returnActualProduction(ProdReq);
                BedroomBehaviour.CleanRooms (StaffProduction);
                //print (ProdReq + ", " +StaffProduction);

                float[] dailyCost = staffMenu.ReturnCostPerDay();
                staffCostMonthlyDP += dailyCost[0];
                staffCostMonthlyHS += dailyCost[1];
                staffCostMonthlyFB += dailyCost[2];
                staffCostMonthlyFD += dailyCost[3];
                staffCostMonthlyCF += dailyCost[4];
                staffCostMonthlyOT += dailyCost[5];

                //adds all 6 staff list's cost daily.
                MasterReference.accountsPayable += (dailyCost[0]+dailyCost[1]+dailyCost[2]
                                                    +dailyCost[3]+dailyCost[4]+dailyCost[5]);

                toolbar.UpdateCredits();
                yield return new WaitForSeconds (debugDayDelay);
            }

        }
        //-----------------------------------SIMULATE THE RESTAURANT-----------------------------------------------//
        //create a new restaurant book with simulated data. 1 month at the time.
        newRestaurantBook =
            GameObject.FindGameObjectWithTag("Restaurant").GetComponent<Restaurant>().SimulateMonth (newMonthlyReport.totalBookings()
                                                                                                    , 7*Calendar.GetNumberOfWeeksInMonth());
        restaurantBooks.Add (newRestaurantBook);//creates a new log for the restaurant numbers. stored inside a list.

        //--------------------------------ASSIGN VALUE OF NEW BALANCE SHEET----------------------------------------//
        BalanceSheet newBalanceSheet =
            new BalanceSheet(Calendar.GetDate(), MasterReference.cashAtBank, MasterReference.accountsReceivable,
                             MasterReference.inventories, MasterReference.totalCurrentAssets(), MasterReference.propretyAndEquipment,
                             MasterReference.totalAssets(), MasterReference.accountsPayable, MasterReference.carbonOffsetReceipts,
                             MasterReference.incomeTaxPayable, MasterReference.dividendOwed, MasterReference.currentMaturityofLongtermDebt,
                             MasterReference.totalCurrentLiabilities(), MasterReference.longTermDebt, MasterReference.shareCapital,
                             MasterReference.retainedEarnings, MasterReference.ownersEquity(), MasterReference.totalLiabilitiesAndOwnersEquity);
        //add date reference for nicer serialization
        Date currentDate = Calendar.GetDate();
        newBalanceSheet.dayOfTheMonth = currentDate.dayOfTheMonth;
        newBalanceSheet.month = currentDate.month;
        newBalanceSheet.year = currentDate.year;
        newBalanceSheet.day = currentDate.day;
        newBalanceSheet.numberOfWeeks = Calendar.GetNumberOfWeeksInMonth(balanceSheets.Count%12);
        balanceSheets.Add(newBalanceSheet);
        //-------------------------------ADD DATA TO MONTHLY REPORT------------------------------------------------//
        newMonthlyReport.restaurantTake = (newRestaurantBook.totalBeverageSales + newRestaurantBook.totalFoodSales);

        refurbishmentTab.refreshTabs ();
        newMonthlyReport.numbRoomLvl1 = MasterReference.standardRooms;
        newMonthlyReport.numbRoomLvl2 = MasterReference.doubleRooms;
        newMonthlyReport.numbRoomLvl3 = MasterReference.deluxeRooms;
        newMonthlyReport.numbRoomLvl4 = MasterReference.suites;
        newMonthlyReport.numbRoomLvl5 = MasterReference.masterSuites;

        newMonthlyReport.expenseDepartmentHeadStaff = staffCostMonthlyDP;
        newMonthlyReport.expenseHotelServicesStaff = staffCostMonthlyHS;
        newMonthlyReport.expenseFoodAndBeverageStaff = staffCostMonthlyFB;
        newMonthlyReport.expenseFrontDeskStaff = staffCostMonthlyFD;
        newMonthlyReport.expenseConferenceStaff = staffCostMonthlyCF;
        newMonthlyReport.expenseOtherStaff = staffCostMonthlyOT;
        //-----------------------------------ADD AMOUNTS FOR END OF MONTH DATA-------------------------------------//
        MasterReference.accountsReceivable += (newRestaurantBook.totalBeverageSales + newRestaurantBook.totalFoodSales);
        MasterReference.accountsPayable += MasterReference.guessComfortMonthlySpending + MasterReference.upgradeCost;//cost of guest comfort amunities.
        //-----------------------------------ADD Account Payable and Receivable at END OF MONTH--------------------//
        MasterReference.cashAtBank -= MasterReference.accountsPayable;
        MasterReference.cashAtBank += MasterReference.accountsReceivable;

        newBalanceSheet.cashAtBank = MasterReference.cashAtBank;

        //---------------------------------------------------------------------------------------------------------//
        bankingTab.GetComponent<BankingReport>().EndMonth();//tick all loan duration down once.
        MasterReference.currentMonthInt++;
        isSimulating = false;
        MasterReference.accountsPayable = 0f;
        adController.Tick();//Ends the month for all ad campaigns and decay/improves hotel exposures.
        //-------------------------------------END OF SIMULATION LOOP---------------------------------------------//

        //------------------------------------------AUTO SAVE-----------------------------------------------------//
        dataProcessor.SaveGame();
        //-------------------------------------RESET SOME DATA----------------------------------------------------//
        MasterReference.upgradeCost = 0f;
    }
Ejemplo n.º 6
0
		/// <summary>
		/// Creates an instance of the FinancialStatements class
		/// </summary>
		public FinancialStatements()
		{
			TotalRiskBasedCapital = new TotalRiskBasedCapital();
			IncomeStatement = new IncomeStatement();
			BalanceSheet = new BalanceSheet();
			CashFlowStatement = new CashFlowStatement();
		}
Ejemplo n.º 7
0
        private BigInteger GetAvailableForSymbol(string symbol)
        {
            var balances = new BalanceSheet(symbol);

            return(balances.Get(this.Storage, this.Address));
        }
Ejemplo n.º 8
0
 public void Add(BalanceSheet balanceSheet)
 {
     balanceSheetList.Add(balanceSheet);
 }
Ejemplo n.º 9
0
        private void OpenOrder(Address from, string baseSymbol, string quoteSymbol, ExchangeOrderSide side, ExchangeOrderType orderType, BigInteger orderSize, BigInteger price)
        {
            Runtime.Expect(IsWitness(from), "invalid witness");

            Runtime.Expect(baseSymbol != quoteSymbol, "invalid base/quote pair");

            Runtime.Expect(Runtime.Nexus.TokenExists(baseSymbol), "invalid base token");
            var baseToken = Runtime.Nexus.GetTokenInfo(baseSymbol);

            Runtime.Expect(baseToken.Flags.HasFlag(TokenFlags.Fungible), "token must be fungible");

            Runtime.Expect(Runtime.Nexus.TokenExists(quoteSymbol), "invalid quote token");
            var quoteToken = Runtime.Nexus.GetTokenInfo(quoteSymbol);

            Runtime.Expect(quoteToken.Flags.HasFlag(TokenFlags.Fungible), "token must be fungible");

            if (orderType != Market)
            {
                Runtime.Expect(orderSize >= GetMinimumTokenQuantity(baseToken), "order size is not sufficient");
                Runtime.Expect(price >= GetMinimumTokenQuantity(quoteToken), "order price is not sufficient");
            }

            var uid = Runtime.Chain.GenerateUID(this.Storage);

            //--------------
            //perform escrow for non-market orders
            string     orderEscrowSymbol = CalculateEscrowSymbol(baseToken, quoteToken, side);
            TokenInfo  orderEscrowToken  = orderEscrowSymbol == baseSymbol ? baseToken : quoteToken;
            BigInteger orderEscrowAmount;
            BigInteger orderEscrowUsage = 0;

            if (orderType == Market)
            {
                orderEscrowAmount = orderSize;
                Runtime.Expect(orderEscrowAmount >= GetMinimumTokenQuantity(orderEscrowToken), "market order size is not sufficient");
            }
            else
            {
                orderEscrowAmount = CalculateEscrowAmount(orderSize, price, baseToken, quoteToken, side);
            }

            //BigInteger baseTokensUnfilled = orderSize;

            var balances = new BalanceSheet(orderEscrowSymbol);
            var balance  = balances.Get(this.Storage, from);

            Runtime.Expect(balance >= orderEscrowAmount, "not enough balance");

            Runtime.Expect(Runtime.Nexus.TransferTokens(Runtime, orderEscrowSymbol, from, Runtime.Chain.Address, orderEscrowAmount), "transfer failed");
            //------------

            var         thisOrder = new ExchangeOrder();
            StorageList orderList;
            BigInteger  orderIndex = 0;

            thisOrder = new ExchangeOrder(uid, Runtime.Time, from, orderSize, baseSymbol, price, quoteSymbol, side, orderType);
            Runtime.Notify(EventKind.OrderCreated, from, uid);

            var key = BuildOrderKey(side, quoteSymbol, baseSymbol);

            orderList  = _orders.Get <string, StorageList>(key);
            orderIndex = orderList.Add <ExchangeOrder>(thisOrder);
            _orderMap.Set <BigInteger, string>(uid, key);

            var makerSide   = side == Buy ? Sell : Buy;
            var makerKey    = BuildOrderKey(makerSide, quoteSymbol, baseSymbol);
            var makerOrders = _orders.Get <string, StorageList>(makerKey);

            do
            {
                int        bestIndex          = -1;
                BigInteger bestPrice          = 0;
                Timestamp  bestPriceTimestamp = 0;

                ExchangeOrder takerOrder = thisOrder;

                var makerOrdersCount = makerOrders.Count();
                for (int i = 0; i < makerOrdersCount; i++)
                {
                    var makerOrder = makerOrders.Get <ExchangeOrder>(i);

                    if (side == Buy)
                    {
                        if (makerOrder.Price > takerOrder.Price && orderType != Market) // too expensive, we wont buy at this price
                        {
                            continue;
                        }

                        if (bestIndex == -1 || makerOrder.Price < bestPrice || (makerOrder.Price == bestPrice && makerOrder.Timestamp < bestPriceTimestamp))
                        {
                            bestIndex          = i;
                            bestPrice          = makerOrder.Price;
                            bestPriceTimestamp = makerOrder.Timestamp;
                        }
                    }
                    else
                    {
                        if (makerOrder.Price < takerOrder.Price && orderType != Market) // too cheap, we wont sell at this price
                        {
                            continue;
                        }

                        if (bestIndex == -1 || makerOrder.Price > bestPrice || (makerOrder.Price == bestPrice && makerOrder.Timestamp < bestPriceTimestamp))
                        {
                            bestIndex          = i;
                            bestPrice          = makerOrder.Price;
                            bestPriceTimestamp = makerOrder.Timestamp;
                        }
                    }
                }

                if (bestIndex >= 0)
                {
                    //since order "uid" has found a match, the creator of this order will be a taker as he will remove liquidity from the market
                    //and the creator of the "bestIndex" order is the maker as he is providing liquidity to the taker
                    var takerAvailableEscrow = orderEscrowAmount - orderEscrowUsage;
                    var takerEscrowUsage     = BigInteger.Zero;
                    var takerEscrowSymbol    = orderEscrowSymbol;

                    var makerOrder        = makerOrders.Get <ExchangeOrder>(bestIndex);
                    var makerEscrow       = _escrows.Get <BigInteger, BigInteger>(makerOrder.Uid);
                    var makerEscrowUsage  = BigInteger.Zero;;
                    var makerEscrowSymbol = orderEscrowSymbol == baseSymbol ? quoteSymbol : baseSymbol;

                    //Get fulfilled order size in base tokens
                    //and then calculate the corresponding fulfilled order size in quote tokens
                    if (takerEscrowSymbol == baseSymbol)
                    {
                        var makerEscrowBaseEquivalent = ConvertQuoteToBase(makerEscrow, makerOrder.Price, baseToken, quoteToken);
                        takerEscrowUsage = takerAvailableEscrow < makerEscrowBaseEquivalent ? takerAvailableEscrow : makerEscrowBaseEquivalent;

                        makerEscrowUsage = CalculateEscrowAmount(takerEscrowUsage, makerOrder.Price, baseToken, quoteToken, Buy);
                    }
                    else
                    {
                        var takerEscrowBaseEquivalent = ConvertQuoteToBase(takerAvailableEscrow, makerOrder.Price, baseToken, quoteToken);
                        makerEscrowUsage = makerEscrow < takerEscrowBaseEquivalent ? makerEscrow : takerEscrowBaseEquivalent;

                        takerEscrowUsage = CalculateEscrowAmount(makerEscrowUsage, makerOrder.Price, baseToken, quoteToken, Buy);
                    }

                    Runtime.Expect(takerEscrowUsage <= takerAvailableEscrow, "Taker tried to use more escrow than available");
                    Runtime.Expect(makerEscrowUsage <= makerEscrow, "Maker tried to use more escrow than available");

                    if (takerEscrowUsage < GetMinimumSymbolQuantity(takerEscrowSymbol) ||
                        makerEscrowUsage < GetMinimumSymbolQuantity(makerEscrowSymbol))
                    {
                        break;
                    }

                    Runtime.Nexus.TransferTokens(Runtime, takerEscrowSymbol, this.Runtime.Chain.Address, makerOrder.Creator, takerEscrowUsage);
                    Runtime.Nexus.TransferTokens(Runtime, makerEscrowSymbol, this.Runtime.Chain.Address, takerOrder.Creator, makerEscrowUsage);

                    Runtime.Notify(EventKind.TokenReceive, makerOrder.Creator, new TokenEventData()
                    {
                        chainAddress = Runtime.Chain.Address, symbol = takerEscrowSymbol, value = takerEscrowUsage
                    });
                    Runtime.Notify(EventKind.TokenReceive, takerOrder.Creator, new TokenEventData()
                    {
                        chainAddress = Runtime.Chain.Address, symbol = makerEscrowSymbol, value = makerEscrowUsage
                    });

                    orderEscrowUsage += takerEscrowUsage;

                    Runtime.Notify(EventKind.OrderFilled, takerOrder.Creator, takerOrder.Uid);
                    Runtime.Notify(EventKind.OrderFilled, makerOrder.Creator, makerOrder.Uid);

                    if (makerEscrowUsage == makerEscrow)
                    {
                        makerOrders.RemoveAt <ExchangeOrder>(bestIndex);
                        _orderMap.Remove(makerOrder.Uid);

                        Runtime.Expect(_escrows.ContainsKey(makerOrder.Uid), "An orderbook entry must have registered escrow");
                        _escrows.Remove(makerOrder.Uid);

                        Runtime.Notify(EventKind.OrderClosed, makerOrder.Creator, makerOrder.Uid);
                    }
                    else
                    {
                        _escrows.Set(makerOrder.Uid, makerEscrow - makerEscrowUsage);
                    }
                }
                else
                {
                    break;
                }
            } while (orderEscrowUsage < orderEscrowAmount);

            var leftoverEscrow = orderEscrowAmount - orderEscrowUsage;

            if (leftoverEscrow == 0 || orderType != Limit)
            {
                orderList.RemoveAt <ExchangeOrder>(orderIndex);
                _orderMap.Remove(thisOrder.Uid);
                _escrows.Remove(thisOrder.Uid);

                if (leftoverEscrow > 0)
                {
                    Runtime.Nexus.TransferTokens(Runtime, orderEscrowSymbol, this.Runtime.Chain.Address, thisOrder.Creator, leftoverEscrow);
                    Runtime.Notify(EventKind.TokenReceive, thisOrder.Creator, new TokenEventData()
                    {
                        chainAddress = Runtime.Chain.Address, symbol = orderEscrowSymbol, value = leftoverEscrow
                    });
                    Runtime.Notify(EventKind.OrderCancelled, thisOrder.Creator, thisOrder.Uid);
                }
                else
                {
                    Runtime.Notify(EventKind.OrderClosed, thisOrder.Creator, thisOrder.Uid);
                }
            }
            else
            {
                _escrows.Set(uid, leftoverEscrow);
            }

            //TODO: ADD FEES, SEND THEM TO Runtime.Chain.Address FOR NOW
        }
Ejemplo n.º 10
0
        public BigInteger Unstake(Address from, BigInteger unstakeAmount)
        {
            Runtime.Expect(IsWitness(from), "witness failed");

            if (!_stakes.ContainsKey <Address>(from))
            {
                return(0);
            }

            var stake = _stakes.Get <Address, EnergyAction>(from);

            if (stake.timestamp.Value == 0) // failsafe, should never happen
            {
                return(0);
            }

            var diff = Runtime.Time - stake.timestamp;
            var days = diff / 86400; // convert seconds to days

            Runtime.Expect(days >= 1, "waiting period required");

            var token    = Runtime.Nexus.GetTokenInfo(Nexus.StakingTokenSymbol);
            var balances = new BalanceSheet(token.Symbol);
            var balance  = balances.Get(this.Storage, Runtime.Chain.Address);

            Runtime.Expect(balance >= unstakeAmount, "not enough balance");

            var availableStake = stake.totalAmount;

            availableStake -= GetStorageStake(from);
            Runtime.Expect(availableStake >= unstakeAmount, "tried to unstake more than what was staked");

            //if this is a partial unstake
            if (availableStake - unstakeAmount > 0)
            {
                Runtime.Expect(availableStake - unstakeAmount >= MinimumValidStake, "leftover stake would be below minimum staking amount");
            }

            Runtime.Expect(balances.Subtract(this.Storage, Runtime.Chain.Address, unstakeAmount), "balance subtract failed");
            Runtime.Expect(balances.Add(this.Storage, from, unstakeAmount), "balance add failed");

            stake.totalAmount -= unstakeAmount;

            var unclaimedPartials = GetLastAction(from).unclaimedPartials;

            if (stake.totalAmount == 0 && unclaimedPartials == 0)
            {
                _stakes.Remove(from);
                _voteHistory.Remove(from);
            }
            else
            {
                var entry = new EnergyAction()
                {
                    unclaimedPartials = unclaimedPartials,
                    totalAmount       = stake.totalAmount,
                    timestamp         = this.Runtime.Time,
                };

                _stakes.Set(from, entry);

                RemoveVotingPower(from, unstakeAmount);
            }

            if (stake.totalAmount < MasterAccountThreshold)
            {
                var count = _mastersList.Count();
                var index = -1;
                for (int i = 0; i < count; i++)
                {
                    var master = _mastersList.Get <EnergyMaster>(i);
                    if (master.address == from)
                    {
                        index = i;
                        break;
                    }
                }

                if (index >= 0)
                {
                    var penalizationDate = GetMasterClaimDateFromReference(1, _mastersList.Get <EnergyMaster>(index).claimDate);
                    _mastersList.RemoveAt <EnergyMaster>(index);

                    Runtime.Notify(EventKind.MasterDemote, from, penalizationDate);
                }
            }

            Runtime.Notify(EventKind.TokenUnstake, from, new TokenEventData()
            {
                chainAddress = Runtime.Chain.Address, symbol = token.Symbol, value = unstakeAmount
            });

            return(unstakeAmount);
        }
Ejemplo n.º 11
0
        public void SwapToken(Address buyer, Address seller, string baseSymbol, string quoteSymbol, BigInteger tokenID, BigInteger price, byte[] signature)
        {
            Runtime.Expect(IsWitness(buyer), "invalid witness");
            Runtime.Expect(seller != buyer, "invalid seller");

            Runtime.Expect(seller.IsUser, "seller must be user address");

            Runtime.Expect(Runtime.Nexus.TokenExists(baseSymbol), "invalid base token");
            var baseToken = Runtime.Nexus.GetTokenInfo(baseSymbol);

            Runtime.Expect(!baseToken.Flags.HasFlag(TokenFlags.Fungible), "token must be non-fungible");

            var ownerships = new OwnershipSheet(baseSymbol);
            var owner      = ownerships.GetOwner(this.Storage, tokenID);

            Runtime.Expect(owner == seller, "invalid owner");

            var swap = new TokenSwap()
            {
                baseSymbol  = baseSymbol,
                quoteSymbol = quoteSymbol,
                buyer       = buyer,
                seller      = seller,
                price       = price,
                value       = tokenID,
            };

            var msg = Serialization.Serialize(swap);

            Runtime.Expect(Ed25519.Verify(signature, msg, seller.PublicKey), "invalid signature");

            Runtime.Expect(Runtime.Nexus.TokenExists(quoteSymbol), "invalid quote token");
            var quoteToken = Runtime.Nexus.GetTokenInfo(quoteSymbol);

            Runtime.Expect(quoteToken.Flags.HasFlag(TokenFlags.Fungible), "token must be fungible");

            var balances = new BalanceSheet(quoteSymbol);
            var balance  = balances.Get(this.Storage, buyer);

            Runtime.Expect(balance >= price, "invalid balance");

            Runtime.Expect(Runtime.Nexus.TransferTokens(Runtime, quoteSymbol, buyer, owner, price), "payment failed");
            Runtime.Expect(Runtime.Nexus.TransferToken(Runtime, baseSymbol, owner, buyer, tokenID), "transfer failed");

            Runtime.Notify(EventKind.TokenSend, seller, new TokenEventData()
            {
                chainAddress = this.Address, symbol = baseSymbol, value = tokenID
            });
            Runtime.Notify(EventKind.TokenSend, buyer, new TokenEventData()
            {
                chainAddress = this.Address, symbol = quoteSymbol, value = price
            });

            Runtime.Notify(EventKind.TokenReceive, seller, new TokenEventData()
            {
                chainAddress = this.Address, symbol = quoteSymbol, value = price
            });
            Runtime.Notify(EventKind.TokenReceive, buyer, new TokenEventData()
            {
                chainAddress = this.Address, symbol = baseSymbol, value = tokenID
            });
        }
        public void CreateAbbreviatedExcelDocument()
        {
            string filename = @"C:\Users\Daniel\Documents\Visual Studio 2012\ExcelFiles\abbreviated_" + DateTime.Now.Year + "_" + DateTime.Now.Month + "_" + DateTime.Now.Day + "_" + DateTime.Now.Hour + DateTime.Now.Minute + ".xlsx";

            FileInfo newFile = new FileInfo(filename);

            using (ExcelPackage xlPackage = new ExcelPackage(newFile))
            {
                string[] columns = AbrreviatedColumns();

                ExcelWorksheet compInfoWS = xlPackage.Workbook.Worksheets.Add("Company Info");

                int i = 1;
                compInfoWS.Row(1).Style.Font.Bold = true;
                foreach (string col in columns)
                {
                    compInfoWS.Cells[1, i].Value = col;
                    i++;
                }

                CompanyCollection comps = CompanyBL.Instance.GetCompanies();

                CompanyValuationStatisticsCollection valuations = new CompanyValuationStatisticsCollection();
                CompanyFinancialStatisticsCollection statistics = new CompanyFinancialStatisticsCollection();
                CompanyValuationStatistics           cvs;

                int count = 2;
                int x     = 0;
                foreach (Company comp in comps)
                {
                    x++;
                    //if (comp.Symbol.Equals("azo"))
                    //{
                    try
                    {
                        cvs = GetCompanyValuationStatistics(comp);
                        valuations.Add(cvs);
                        CompanyFinancialStatistics stats = CompanyFinancialStatisticsBL.Instance.GetCompanyFinancialStatistics(comp.Symbol, DateTime.Today.AddDays(-1));
                        statistics.Add(stats);
                        BalanceSheet      bal  = BalanceSheetBL.Instance.GetBalanceSheet(comp.Symbol, 2012);
                        IncomeStatement   inc  = IncomeStatementBL.Instance.GetIncomeStatement(comp.Symbol, 2012);
                        CompanyAnnualData data = CompanyAnnualDataBL.Instance.GetCompanyAnnual(comp.Symbol, 2012);

                        int f = 1;

                        compInfoWS.Cells[count, f++].Value   = comp.Symbol;
                        compInfoWS.Cells[count, f++].Value   = comp.CompanyName;
                        compInfoWS.Cells[count, f++].Value   = comp.Industry;
                        compInfoWS.Cells[count, f++].Value   = comp.Sector;
                        compInfoWS.Cells[count, f++].Value   = stats.StockPrice;
                        compInfoWS.Cells[count, f++].Value   = stats.BookValuePerShare;
                        compInfoWS.Cells[count, f++].Value   = stats.ReturnOnEquity;
                        compInfoWS.Cells[count, f++].Value   = stats.ReturnOnAssets;
                        compInfoWS.Cells[count, f++].Value   = stats.DebtToEquity;
                        compInfoWS.Cells[count, f++].Value   = stats.YearHigh;
                        compInfoWS.Cells[count, f++].Value   = stats.YearLow;
                        compInfoWS.Cells[count, f++].Value   = stats.Eps;
                        compInfoWS.Cells[count, f++].Value   = stats.RevenuePerShare;
                        compInfoWS.Cells[count, f++].Value   = stats.AverageVolume;
                        compInfoWS.Cells[count, f++].Value   = stats.MarketCap;
                        compInfoWS.Cells[count, f++].Value   = stats.TotalDebt;
                        compInfoWS.Cells[count, f++].Value   = stats.CurrentSharesShort;
                        compInfoWS.Cells[count, f++].Value   = stats.LastMonthSharesShort;
                        compInfoWS.Cells[count, f++].Value   = (stats.CurrentSharesShort / data.SharesOutstanding);
                        compInfoWS.Cells[count, f++].Value   = (stats.LastMonthSharesShort / data.SharesOutstanding);
                        compInfoWS.Cells[count, f++].Value   = stats.FiftyMovingAverage;
                        compInfoWS.Cells[count, f++].Value   = stats.TwoHundredMovingAverage;
                        compInfoWS.Cells[count, f++].Value   = stats.DividendYieldPercent;
                        compInfoWS.Cells[count, f++].Value   = stats.OperatingMargin;
                        compInfoWS.Cells[count, f++].Value   = stats.ProfitMargin;
                        compInfoWS.Cells[count, f++].Value   = stats.TrailingPE;
                        compInfoWS.Cells[count, f++].Value   = stats.ForwardPE;
                        compInfoWS.Cells[count, f++].Value   = stats.PegRatio;
                        compInfoWS.Cells[count, f++].Value   = stats.EnterpriseValue;
                        compInfoWS.Cells[count, f++].Value   = stats.PriceToSales;
                        compInfoWS.Cells[count, f++].Value   = stats.PriceToBook;
                        compInfoWS.Cells[count, f++].Value   = stats.EvToRevenue;
                        compInfoWS.Cells[count, f++].Value   = stats.EvToEbitda;
                        compInfoWS.Cells[count, f++].Value   = stats.QuarterlyRevenueGrowth;
                        compInfoWS.Cells[count, f++].Value   = stats.QuarterlyEarningsGrowth;
                        compInfoWS.Cells[count, f++].Value   = stats.NetIncomeToCommonShares;
                        compInfoWS.Cells[count, f++].Value   = stats.TotalCash;
                        compInfoWS.Cells[count, f++].Value   = stats.CurrentRatio;
                        compInfoWS.Cells[count, f++].Value   = stats.OperatingCashFlow;
                        compInfoWS.Cells[count, f++].Value   = stats.LeveredCashFlow;
                        compInfoWS.Cells[count, f++].Value   = stats.Roic();
                        compInfoWS.Cells[count, f++].Value   = inc.Ebit;
                        compInfoWS.Cells[count, f++].Value   = cvs.NopDcfsAvgGrowth.GetAverage("StockValue");
                        compInfoWS.Cells[count, f++].Value   = cvs.NopDcfsAvgGrowth.GetStandardDeviation("StockValue");
                        compInfoWS.Cells[count, f++].Value   = string.Format("={0}/{1}", compInfoWS.Cells[count, 43].Address, compInfoWS.Cells[count, 44].Address);
                        compInfoWS.Cells[count, f++].Value   = cvs.NopDcfsDecayGrowth.GetAverage("StockValue");
                        compInfoWS.Cells[count, f++].Value   = cvs.NopDcfsDecayGrowth.GetStandardDeviation("StockValue");
                        compInfoWS.Cells[count, f++].Value   = string.Format("={0}/{1}", compInfoWS.Cells[count, 46].Address, compInfoWS.Cells[count, 47].Address);
                        compInfoWS.Cells[count, f++].Value   = cvs.NopDcfsNoGrowth.GetAverage("StockValue");
                        compInfoWS.Cells[count, f++].Value   = cvs.NopDcfsNoGrowth.GetStandardDeviation("StockValue");
                        compInfoWS.Cells[count, f++].Value   = string.Format("={0}/{1}", compInfoWS.Cells[count, 49].Address, compInfoWS.Cells[count, 50].Address);
                        compInfoWS.Cells[count, f++].Value   = cvs.NetIncomeDcfsAvgGrowth.GetAverage("StockValue");
                        compInfoWS.Cells[count, f++].Value   = cvs.NetIncomeDcfsAvgGrowth.GetStandardDeviation("StockValue");
                        compInfoWS.Cells[count, f++].Value   = string.Format("={0}/{1}", compInfoWS.Cells[count, 52].Address, compInfoWS.Cells[count, 53].Address);
                        compInfoWS.Cells[count, f++].Value   = cvs.NetIncomeDcfsDecayGrowth.GetAverage("StockValue");
                        compInfoWS.Cells[count, f++].Value   = cvs.NetIncomeDcfsDecayGrowth.GetStandardDeviation("StockValue");
                        compInfoWS.Cells[count, f++].Value   = string.Format("={0}/{1}", compInfoWS.Cells[count, 55].Address, compInfoWS.Cells[count, 56].Address);
                        compInfoWS.Cells[count, f++].Value   = cvs.NetIncomeDcfsNoGrowth.GetAverage("StockValue");
                        compInfoWS.Cells[count, f++].Value   = cvs.NetIncomeDcfsNoGrowth.GetStandardDeviation("StockValue");
                        compInfoWS.Cells[count, f++].Value   = string.Format("={0}/{1}", compInfoWS.Cells[count, 58].Address, compInfoWS.Cells[count, 59].Address);
                        compInfoWS.Cells[count, f++].Formula = string.Format("= {0} - {1}", compInfoWS.Cells[count, 6].Address, compInfoWS.Cells[count, 5].Address);
                        compInfoWS.Cells[count, f++].Formula = string.Format("= {0} - {1}", compInfoWS.Cells[count, 43].Address, compInfoWS.Cells[count, 5].Address);
                        compInfoWS.Cells[count, f++].Formula = string.Format("= {0} - {1}", compInfoWS.Cells[count, 46].Address, compInfoWS.Cells[count, 5].Address);
                        compInfoWS.Cells[count, f++].Formula = string.Format("= {0} - {1}", compInfoWS.Cells[count, 49].Address, compInfoWS.Cells[count, 5].Address);
                        compInfoWS.Cells[count, f++].Formula = string.Format("= {0} - {1}", compInfoWS.Cells[count, 52].Address, compInfoWS.Cells[count, 5].Address);
                        compInfoWS.Cells[count, f++].Formula = string.Format("= {0} - {1}", compInfoWS.Cells[count, 55].Address, compInfoWS.Cells[count, 5].Address);
                        compInfoWS.Cells[count, f++].Formula = string.Format("= {0} - {1}", compInfoWS.Cells[count, 58].Address, compInfoWS.Cells[count, 5].Address);

                        count++;
                        Console.WriteLine("loaded: {0}", comp.Symbol);
                    }
                    catch (Exception ex)
                    { Console.WriteLine(string.Format("ERROR: DID NOT LOAD: {0} {1}", comp.Symbol, ex.Message)); }
                    //}
                }

                xlPackage.Save();
            }
        }
Ejemplo n.º 13
0
        public void SpendGas(Address from)
        {
            if (Runtime.readOnlyMode)
            {
                return;
            }

            Runtime.Expect(IsWitness(from), "invalid witness");

            Runtime.Expect(_allowanceMap.ContainsKey(from), "no gas allowance found");

            var availableAmount = _allowanceMap.Get <Address, BigInteger>(from);

            var spentGas       = Runtime.UsedGas;
            var requiredAmount = spentGas * Runtime.GasPrice;

            Runtime.Expect(availableAmount >= requiredAmount, "gas allowance is not enough");

            /*var token = this.Runtime.Nexus.FuelToken;
             * Runtime.Expect(token != null, "invalid token");
             * Runtime.Expect(token.Flags.HasFlag(TokenFlags.Fungible), "must be fungible token");
             */

            var balances = new BalanceSheet(Nexus.FuelTokenSymbol);

            var leftoverAmount = availableAmount - requiredAmount;

            var        targetAddress = _allowanceTargets.Get <Address, Address>(from);
            BigInteger targetGas;

            if (targetAddress != Address.Null)
            {
                targetGas = spentGas / 2; // 50% for dapps
            }
            else
            {
                targetGas = 0;
            }

            // TODO the transfers around here should pass through Nexus.TransferTokens!!
            // return unused gas to transaction creator
            if (leftoverAmount > 0)
            {
                Runtime.Expect(balances.Subtract(this.Storage, Runtime.Chain.Address, leftoverAmount), "gas leftover deposit failed");
                Runtime.Expect(balances.Add(this.Storage, from, leftoverAmount), "gas leftover withdraw failed");
            }

            if (targetGas > 0)
            {
                var targetPayment = targetGas * Runtime.GasPrice;
                Runtime.Expect(balances.Subtract(this.Storage, Runtime.Chain.Address, targetPayment), "gas target withdraw failed");
                Runtime.Expect(balances.Add(this.Storage, targetAddress, targetPayment), "gas target deposit failed");
                spentGas -= targetGas;
            }

            _allowanceMap.Remove(from);
            _allowanceTargets.Remove(from);

            if (targetGas > 0)
            {
                Runtime.Notify(EventKind.GasPayment, targetAddress, new GasEventData()
                {
                    address = from, price = Runtime.GasPrice, amount = targetGas
                });
            }

            Runtime.Notify(EventKind.GasPayment, Runtime.Chain.Address, new GasEventData()
            {
                address = from, price = Runtime.GasPrice, amount = spentGas
            });
        }
Ejemplo n.º 14
0
        public void TestBalanceSheetWithLogicalAccounts()
        {
            ILoggerFactory loggerFactory = new LoggerFactory();

            using (var sqliteMemoryWrapper = new SqliteMemoryWrapper())
            {
                var currencyFactory   = new CurrencyFactory();
                var usdCurrencyEntity = currencyFactory.Create(CurrencyPrefab.Usd, true);
                currencyFactory.Add(sqliteMemoryWrapper.DbContext, usdCurrencyEntity);

                var accountFactory = new AccountFactory();
                Entities.Account incomeAccountEntity =
                    accountFactory.Create(AccountPrefab.Income, usdCurrencyEntity);
                Entities.Account checkingAccountEntity =
                    accountFactory.Create(AccountPrefab.Checking, usdCurrencyEntity);
                Entities.Account rentPrepaymentAccountEntity =
                    accountFactory.Create(AccountPrefab.RentPrepayment, usdCurrencyEntity);
                Entities.Account groceriesPrepaymentAccountEntity =
                    accountFactory.Create(AccountPrefab.GroceriesPrepayment, usdCurrencyEntity);
                accountFactory.Add(sqliteMemoryWrapper.DbContext, incomeAccountEntity);
                accountFactory.Add(sqliteMemoryWrapper.DbContext, checkingAccountEntity);
                accountFactory.Add(sqliteMemoryWrapper.DbContext, rentPrepaymentAccountEntity);
                accountFactory.Add(sqliteMemoryWrapper.DbContext, groceriesPrepaymentAccountEntity);

                var checkingToRentPrepaymentRelationship = new Entities.AccountRelationship
                {
                    SourceAccount      = checkingAccountEntity,
                    DestinationAccount = rentPrepaymentAccountEntity,
                    Type = AccountRelationshipType.PhysicalToLogical
                };
                var checkingToGroceriesPrepaymentRelationship = new Entities.AccountRelationship
                {
                    SourceAccount      = checkingAccountEntity,
                    DestinationAccount = groceriesPrepaymentAccountEntity,
                    Type = AccountRelationshipType.PhysicalToLogical
                };

                sqliteMemoryWrapper.DbContext.AccountRelationships.Add(checkingToRentPrepaymentRelationship);
                sqliteMemoryWrapper.DbContext.AccountRelationships.Add(checkingToGroceriesPrepaymentRelationship);
                sqliteMemoryWrapper.DbContext.SaveChanges();

                var transactions = new Entities.Transaction[]
                {
                    new Entities.Transaction
                    {
                        CreditAccount = incomeAccountEntity,
                        DebitAccount  = checkingAccountEntity,
                        Amount        = 100m,
                        At            = new DateTime(2018, 1, 1)
                    },// income=100CR,checking=100DR
                    new Entities.Transaction
                    {
                        CreditAccount = checkingAccountEntity,
                        DebitAccount  = rentPrepaymentAccountEntity,
                        Amount        = 40m,
                        At            = new DateTime(2018, 1, 1)
                    },// income=100CR,(checking=60DR,rent-prepayment=40DR)=100DR
                    new Entities.Transaction
                    {
                        CreditAccount = checkingAccountEntity,
                        DebitAccount  = groceriesPrepaymentAccountEntity,
                        Amount        = 20m,
                        At            = new DateTime(2018, 1, 1)
                    }// income=100CR,(checking=40DR,rent-prepayment=40DR,groceries-prepayment=20DR)=100DR
                };
                sqliteMemoryWrapper.DbContext.Transactions.AddRange(transactions);
                sqliteMemoryWrapper.DbContext.SaveChanges();

                var accountService = new AccountService(
                    loggerFactory,
                    sqliteMemoryWrapper.DbContext
                    );
                var currencyService = new CurrencyService(
                    loggerFactory,
                    sqliteMemoryWrapper.DbContext
                    );
                var balanceSheetService = new BalanceSheetService(
                    loggerFactory,
                    sqliteMemoryWrapper.DbContext
                    );

                BalanceSheet            balanceSheet            = balanceSheetService.Generate(new DateTime(2018, 1, 1));
                List <BalanceSheetItem> balanceSheetAssets      = balanceSheet.Assets.ToList();
                List <BalanceSheetItem> balanceSheetLiabilities = balanceSheet.Liabilities.ToList();

                Assert.AreEqual(usdCurrencyEntity.Symbol, balanceSheet.CurrencySymbol);
                Assert.AreEqual(100, balanceSheet.TotalAssets);
                Assert.AreEqual(0, balanceSheet.TotalLiabilities);
                Assert.AreEqual(100, balanceSheet.NetWorth);
                Assert.AreEqual(1, balanceSheetAssets.Count);
                Assert.AreEqual(0, balanceSheetLiabilities.Count);
                Assert.AreEqual(checkingAccountEntity.Name, balanceSheetAssets[0].Name);
                Assert.AreEqual(100, balanceSheetAssets[0].Balance);
            }
        }
        public void PopulateCompanyFinancialStatisticsFromStatements(CompanyFinancialStatistics finStats, IncomeStatement inc, BalanceSheet bs, CompanyAnnualData cad)
        {
            finStats.BookValuePerShare = bs.ShareholdersEquity / cad.SharesOutstanding;
            finStats.DebtToEquity      = bs.Debt / bs.ShareholdersEquity;
            finStats.ProfitMargin      = inc.NetIncome / inc.Revenue;
            finStats.ReturnOnAssets    = inc.NetIncome / bs.TotalAssets;

            if (bs.ShareholdersEquity == 0)
            {
                finStats.ReturnOnEquity = 0;
            }
            else
            {
                finStats.ReturnOnEquity = inc.NetIncome / bs.ShareholdersEquity;
            }

            finStats.RevenuePerShare = inc.Revenue / cad.SharesOutstanding;
            finStats.TotalDebt       = bs.Debt;
        }
Ejemplo n.º 16
0
        internal BalanceSheet PopulateFinancialStatement(BalanceSheetFilterItem item, BalanceSheet bs)
        {
            bs.CurrentAssets      = GetMaxValue(item.CurrentAssetsItems);
            bs.CurrentLiabilities = GetMaxValue(item.CurrentLiabilitiesItems);
            bs.Debt = GetMaxValue(item.DebtItems);
            bs.Ppe  = GetMaxValue(item.PpeItems);
            bs.ShareholdersEquity = GetMaxValue(item.ShareholderEquityItems);
            bs.Cash        = GetMaxValue(item.CashItems);
            bs.TotalAssets = GetMaxValue(item.TotalAssetsItems);

            return(bs);
        }
Ejemplo n.º 17
0
    public BalanceSheet deepCopy()
    {
        BalanceSheet newSheet = new BalanceSheet();

        newSheet.dateOfReport = this.dateOfReport;
        newSheet.cashAtBank = this.cashAtBank;
        newSheet.accountsReceivable = this.accountsReceivable;
        newSheet.inventories = this.inventories;
        newSheet.totalCurrentAssets = this.totalCurrentAssets;
        newSheet.propretyAndEquipment = this.propretyAndEquipment;
        newSheet.totalAssets = this.totalAssets;
        newSheet.accountsPayable = this.accountsPayable;
        newSheet.carbonOffsetReceipts = this.carbonOffsetReceipts;
        newSheet.incomeTaxPayable = this.incomeTaxPayable;
        newSheet.dividendOwed = this.dividendOwed;
        newSheet.currentMaturityofLongtermDebt = this.currentMaturityofLongtermDebt;
        newSheet.totalCurrentLiabilities = this.totalCurrentLiabilities;
        newSheet.longTermDebt = this.longTermDebt;
        newSheet.shareCapital = this.shareCapital;
        newSheet.retainedEarnings = this.retainedEarnings;
        newSheet.ownersEquity = this.ownersEquity;
        newSheet.totalLiabilitiesAndOwnersEquity = this.totalLiabilitiesAndOwnersEquity;

        return newSheet;
    }
 public HttpResponseMessage Lock(BalanceSheet row)
 {
     _process.Lock(row, UpdatedId);
     return(Request.CreateResponse(HttpStatusCode.OK));
 }
Ejemplo n.º 19
0
        public void CloseBlock(Block block, StorageChangeSetContext storage)
        {
            var rootStorage = this.IsRoot ? storage : Nexus.RootStorage;

            if (block.Height > 1)
            {
                var prevBlock = GetBlockByHash(block.PreviousHash);

                if (prevBlock.Validator != block.Validator)
                {
                    block.Notify(new Event(EventKind.ValidatorSwitch, block.Validator, "block", Serialization.Serialize(prevBlock)));
                }
            }

            var balance        = new BalanceSheet(DomainSettings.FuelTokenSymbol);
            var blockAddress   = Address.FromHash("block");
            var totalAvailable = balance.Get(storage, blockAddress);

            var targets = new List <Address>();

            if (Nexus.HasGenesis)
            {
                var validators = Nexus.GetValidators();

                var totalValidators = Nexus.GetPrimaryValidatorCount();

                for (int i = 0; i < totalValidators; i++)
                {
                    var validator = validators[i];
                    if (validator.type != ValidatorType.Primary)
                    {
                        continue;
                    }

                    targets.Add(validator.address);
                }
            }
            else
            if (totalAvailable > 0)
            {
                targets.Add(Nexus.GetGenesisAddress(rootStorage));
            }

            if (targets.Count > 0)
            {
                if (!balance.Subtract(storage, blockAddress, totalAvailable))
                {
                    throw new BlockGenerationException("could not subtract balance from block address");
                }

                var amountPerValidator = totalAvailable / targets.Count;
                var leftOvers          = totalAvailable - (amountPerValidator * targets.Count);

                foreach (var address in targets)
                {
                    BigInteger amount = amountPerValidator;

                    if (address == block.Validator)
                    {
                        amount += leftOvers;
                    }

                    // TODO this should use triggers when available...
                    if (!balance.Add(storage, address, amount))
                    {
                        throw new BlockGenerationException($"could not add balance to {address}");
                    }

                    var eventData = Serialization.Serialize(new TokenEventData(DomainSettings.FuelTokenSymbol, amount, this.Name));
                    block.Notify(new Event(EventKind.TokenClaim, address, "block", eventData));
                }
            }
        }
Ejemplo n.º 20
0
 public void Add(BalanceSheet transaction)
 {
     _trasactionRepository.Add(transaction);
 }
Ejemplo n.º 21
0
        public ReportObjectData ReadRow(IInputData input)
        {
            DataRow row = Query(input.QueryString);
            string type = row["ReportName"].ToString();
            Object obj = null;
            switch (type)
            {
                case "BalanceSheet":
                    obj = new BalanceSheet();
                    break;
                case "CashFlowStatement":
                    obj = new CashFlowStatement();
                    break;
                //case "ProfitAppropriation":
                //    obj = new IncomeStatement();
                //    break;
                case "IncomeStatement":
                    obj = new IncomeStatement();
                    break;
            }
            ReportObjectData result = new ReportObjectData(row, obj);

            return result;
        }
Ejemplo n.º 22
0
 public void Update(BalanceSheet transaction)
 {
     _trasactionRepository.Update(transaction);
 }
Ejemplo n.º 23
0
 static BalanceSheet balancesheetDB( KNMFin.Google.BalanceSheet bs )
 {
     var bsDB = new BalanceSheet();
     bsDB.Accounts_Payable = bs.Accounts_Payable;
     bsDB.Accounts_Receivable__Trade__Net = bs.Accounts_Receivable__Trade__Net;
     bsDB.Accrued_Expenses = bs.Accrued_Expenses;
     bsDB.Accumulated_Depreciation__Total = bs.Accumulated_Depreciation__Total;
     bsDB.Additional_PaidIn_Capital = bs.Additional_PaidIn_Capital;
     bsDB.Annual = bs.Period == Period.Annual ? true : false;
     bsDB.Capital_Lease_Obligations = bs.Capital_Lease_Obligations;
     bsDB.Cash_and_Equivalents = bs.Cash_and_Equivalents;
     bsDB.Cash_and_Short_Term_Investments = bs.Cash_and_Short_Term_Investments;
     bsDB.Common_Stock__Total = bs.Common_Stock__Total;
     bsDB.Current_Port_of_LT_Debt_and_Capital_Leases = bs.Current_Port_of_LT_Debt_and_Capital_Leases;
     bsDB.Deferred_Income_Tax = bs.Deferred_Income_Tax;
     bsDB.Goodwill__Net = bs.Goodwill__Net;
     bsDB.Intangibles__Net = bs.Intangibles__Net;
     bsDB.Long_Term_Debt = bs.Long_Term_Debt;
     bsDB.Long_Term_Investments = bs.Long_Term_Investments;
     bsDB.Minority_Interest = bs.Minority_Interest;
     bsDB.Notes_Payable_and_Short_Term_Debt = bs.Notes_Payable_and_Short_Term_Debt;
     bsDB.Other_Current_Assets__Total = bs.Other_Current_Assets__Total;
     bsDB.Other_Current_liabilities__Total = bs.Other_Current_liabilities__Total;
     bsDB.Other_Equity__Total = bs.Other_Equity__Total;
     bsDB.Other_Liabilities__Total = bs .Other_Liabilities__Total;
     bsDB.Other_Long_Term_Assets__Total = bs.Other_Long_Term_Assets__Total;
     bsDB.Receivables__Other = bs.Receivables__Other;
     bsDB.Redeemable_Preferred_Stock__Total = bs.Redeemable_Preferred_Stock__Total;
     bsDB.Retained_Earnings__Accumulated_Deficit_ = bs.Redeemable_Preferred_Stock__Total;
     bsDB.Shares_Outs__Common_Stock_Primary_Issue = bs.Shares_Outs__Common_Stock_Primary_Issue;
     bsDB.Short_Term_Investments = bs.Short_Term_Investments;
     bsDB.Total_Assets = bs.Total_Assets;
     bsDB.Total_Common_Shares_Outstanding = bs.Total_Common_Shares_Outstanding;
     bsDB.Total_Current_Assets = bs.Total_Current_Assets;
     bsDB.Total_Current_Liabilities = bs.Total_Current_Liabilities;
     bsDB.Total_Debt = bs.Total_Debt;
     bsDB.Total_Equity = bs.Total_Equity;
     bsDB.Total_Inventory = bs.Total_Inventory;
     bsDB.Total_Liabilities = bs.Total_Liabilities;
     bsDB.Total_Liabilities_and_Shareholders_Equity = bs.Total_Liabilities_and_Shareholders_Equity;
     bsDB.Total_Long_Term_Debt = bs.Total_Long_Term_Debt;
     bsDB.Total_Receivables__Net = bs.Total_Receivables__Net;
     bsDB.Treasury_Stock__Common = bs.Treasury_Stock__Common;
     bsDB.Prepaid_Expenses = bs.Prepaid_Expenses;
     bsDB.Preferred_Stock__Non_Redeemable__Net = bs.Preferred_Stock__Non_Redeemable__Net;
     bsDB.Property_and_Plant_and_Equipment__Total__Gross = bs.Property_and_Plant_and_Equipment__Total__Gross;
     bsDB.PeriodEnd = bs.PeriodEnd;
     return bsDB;
 }
Ejemplo n.º 24
0
        internal bool TransferTokens(RuntimeVM runtimeVM, string symbol, Address source, Address destination, BigInteger amount)
        {
            if (!TokenExists(symbol))
            {
                return(false);
            }

            var tokenInfo = GetTokenInfo(symbol);

            if (!tokenInfo.Flags.HasFlag(TokenFlags.Transferable))
            {
                throw new Exception("Not transferable");
            }

            if (!tokenInfo.Flags.HasFlag(TokenFlags.Fungible))
            {
                throw new Exception("Should be fungible");
            }

            if (amount <= 0)
            {
                return(false);
            }

            var balances = new BalanceSheet(symbol);

            if (!balances.Subtract(runtimeVM.ChangeSet, source, amount))
            {
                return(false);
            }

            if (!balances.Add(runtimeVM.ChangeSet, destination, amount))
            {
                return(false);
            }

            var tokenTriggerResult = SmartContract.InvokeTrigger(runtimeVM, tokenInfo.Script, TokenContract.TriggerSend, source, amount);

            if (!tokenTriggerResult)
            {
                return(false);
            }

            tokenTriggerResult = SmartContract.InvokeTrigger(runtimeVM, tokenInfo.Script, TokenContract.TriggerReceive, destination, amount);
            if (!tokenTriggerResult)
            {
                return(false);
            }

            var accountScript        = this.LookUpAddressScript(source);
            var accountTriggerResult = SmartContract.InvokeTrigger(runtimeVM, accountScript, AccountContract.TriggerSend, source, amount);

            if (!accountTriggerResult)
            {
                return(false);
            }

            accountScript        = this.LookUpAddressScript(destination);
            accountTriggerResult = SmartContract.InvokeTrigger(runtimeVM, accountScript, AccountContract.TriggerSend, destination, amount);
            if (!accountTriggerResult)
            {
                return(false);
            }

            return(true);
        }
Ejemplo n.º 25
0
        private BalanceSheet ExtractBalanceSheet(Repository repo)
        {
            //Can add a date here in declaration

               var report = new XeroApi.Model.Reporting.BalanceSheetReport();

               var balanceSheetReport = repo.Reports.RunDynamicReport(report);

               var sectionRows = balanceSheetReport.Rows.Where(r => r.RowType == "Section");

               //Assets
               var bankEntries = ExtractSectionData(sectionRows.First(r => r.Title == "Bank"), "Bank", true);
               var currentAssetEntries = ExtractSectionData(sectionRows.First(r => r.Title == "Current Assets"), "Current Asset", true);
               var fixedAssetEntries = ExtractSectionData(sectionRows.First(r => r.Title == "Fixed Assets"), "Fixed Asset", true);

               //Liabilites
               var currentLiabilities = ExtractSectionData(sectionRows.First(r => r.Title == "Current Liabilities"), "Current Liability", false);
               var nonCurrentLiabilities = ExtractSectionData(sectionRows.First(r => r.Title == "Non-Current Liabilities"), "Non-Current Liability", false);

               var latestBalanceSheet = new BalanceSheet();

               latestBalanceSheet.BalanceSheetEntries = new List<BalanceSheetEntry>();
               latestBalanceSheet.BalanceSheetEntries.AddRange(bankEntries);
               latestBalanceSheet.BalanceSheetEntries.AddRange(currentAssetEntries);
               latestBalanceSheet.BalanceSheetEntries.AddRange(fixedAssetEntries);
               latestBalanceSheet.BalanceSheetEntries.AddRange(currentLiabilities);
               latestBalanceSheet.BalanceSheetEntries.AddRange(nonCurrentLiabilities);

               return latestBalanceSheet;
        }
Ejemplo n.º 26
0
        public void BuyToken(Address from, string symbol, BigInteger tokenID)
        {
            Runtime.Expect(IsWitness(from), "invalid witness");

            var auctionID = symbol + "." + tokenID;

            Runtime.Expect(_auctionMap.ContainsKey <string>(auctionID), "invalid auction");
            var auction = _auctionMap.Get <string, MarketAuction>(auctionID);

            Runtime.Expect(Runtime.Nexus.TokenExists(auction.BaseSymbol), "invalid base token");
            var baseToken = Runtime.Nexus.GetTokenInfo(auction.BaseSymbol);

            Runtime.Expect(!baseToken.Flags.HasFlag(TokenFlags.Fungible), "token must be non-fungible");

            var nft = Runtime.Nexus.GetNFT(symbol, tokenID);

            Runtime.Expect(nft.CurrentChain == Runtime.Chain.Address, "token not currently in this chain");
            Runtime.Expect(nft.CurrentOwner == this.Address, "invalid owner");

            if (auction.Creator != from)
            {
                Runtime.Expect(Runtime.Nexus.TokenExists(auction.QuoteSymbol), "invalid quote token");
                var quoteToken = Runtime.Nexus.GetTokenInfo(auction.QuoteSymbol);
                Runtime.Expect(quoteToken.Flags.HasFlag(TokenFlags.Fungible), "quote token must be fungible");

                var balances = new BalanceSheet(quoteToken.Symbol);
                var balance  = balances.Get(this.Storage, from);
                Runtime.Expect(balance >= auction.Price, "not enough balance");

                Runtime.Expect(Runtime.Nexus.TransferTokens(Runtime, quoteToken.Symbol, from, auction.Creator, auction.Price), "payment failed");
            }

            Runtime.Expect(Runtime.Nexus.TransferToken(Runtime, baseToken.Symbol, this.Address, from, auction.TokenID), "transfer failed");

            _auctionMap.Remove <string>(auctionID);
            _auctionIDs.Remove(auctionID);

            if (auction.Creator == from)
            {
                Runtime.Notify(EventKind.OrderCancelled, from, new MarketEventData()
                {
                    ID = auction.TokenID, BaseSymbol = auction.BaseSymbol, QuoteSymbol = auction.QuoteSymbol, Price = 0
                });
            }
            else
            {
                Runtime.Notify(EventKind.TokenSend, from, new TokenEventData()
                {
                    chainAddress = this.Address, symbol = auction.QuoteSymbol, value = auction.Price
                });
                Runtime.Notify(EventKind.TokenReceive, auction.Creator, new TokenEventData()
                {
                    chainAddress = this.Address, symbol = auction.QuoteSymbol, value = auction.Price
                });

                Runtime.Notify(EventKind.OrderFilled, from, new MarketEventData()
                {
                    ID = auction.TokenID, BaseSymbol = auction.BaseSymbol, QuoteSymbol = auction.QuoteSymbol, Price = auction.Price
                });
            }

            Runtime.Notify(EventKind.TokenReceive, from, new TokenEventData()
            {
                chainAddress = this.Address, symbol = auction.BaseSymbol, value = auction.TokenID
            });
        }