Ejemplo n.º 1
0
        public void AddTransaction(long orderId, Instrument instrument, double openPrice, double?stopLoss, double?takeProfit, decimal volumen, TypeTransaction typeTransaction, DateTime dateOpen, string info)
        {
            var position = new Position(openPrice, volumen);

            if (orderId <= 0)
            {
                orderId = GetMaxOrderId();
            }
            var transaction = new Transaction(orderId, instrument, position, typeTransaction, dateOpen, info);

            if (stopLoss != null && stopLoss > 0)
            {
                transaction.Position.SetStopLoss(stopLoss ?? 0);
            }
            if (takeProfit != null && takeProfit > 0)
            {
                transaction.Position.SetTakeProfit(takeProfit ?? 0);
            }
            Transactions.Add(transaction);
            AddDomainEvent(new AccountAddedNewTransactionDomainEvent(transaction, this));
        }
Ejemplo n.º 2
0
 public void GetPaymentFromCar()
 {
     //It has sense when will be a lot of cars in parking
     //Parallel.ForEach(Cars, (car, state, index) =>
     //{
     //    decimal sum = Settings.Prices.Where(x => x.Key == car.CarType).Select(x => x.Value).FirstOrDefault();
     //    if (car.Balance < sum) sum = sum * Settings.Fine;
     //    var transaction = new Transaction(car.Id, sum);
     //    Transactions.Add(transaction);
     //});
     foreach (var car in Cars)
     {
         decimal sum = Settings.Prices.Where(x => x.Key == car.CarType).Select(x => x.Value).FirstOrDefault();
         if (car.Balance < sum)
         {
             sum = sum * Settings.Fine;
         }
         var transaction = new Transaction(car.Id, sum);
         Transactions.Add(transaction);
     }
 }
        /// <summary>
        /// All transactions are added to the collection through this method so that the running balance
        /// can be calculated based on the previous transaction
        /// </summary>
        /// <param name="transaction"></param>
        void AddTransaction(Transaction transaction)
        {
            //find the preceding transaction
            var precedingTransaction = Transactions.Where(t => t.Date & lt; transaction.Date)
                                       .OrderByDescending(t => t.Date)
                                       .FirstOrDefault();

            if (precedingTransaction == null)
            {
                //This is the earliest transaction so calc based on starting balance
                transaction.RunningBalance = StartingBalance + transaction.Amount;
            }
            else
            {
                //this is not the earliest transaction so calc based on previous
                transaction.RunningBalance = precedingTransaction.RunningBalance + transaction.Amount;
            }

            //Add the transactions to the collection with the calculated balance
            Transactions.Add(transaction);
        }
Ejemplo n.º 4
0
        public void Withdraw(decimal value)
        {
            if (!Active)
            {
                throw new AccountBlockedException();
            }

            if (value > WithdrawLimit)
            {
                throw new WithdrawLimitExceededException();
            }

            if (value > Balance)
            {
                throw new BalanceInsufficientException();
            }

            Transactions.Add(new Transaction {
                TransactionDate = DateTime.Now, Value = value * -1
            });
        }
Ejemplo n.º 5
0
 public bool PerformTransaction(Transaction t)
 {
     if (t.Transmitter == this || t.Receiver == this)
     {
         if (t.Transmitter.Balance >= t.Ammount)
         {
             t.Transmitter.Balance -= t.Ammount;
             t.Receiver.Balance    += t.Ammount;
             Transactions.Add(t);
             return(true);
         }
         else
         {
             throw new ArgumentException("Transaction ammount exceeds the balance of transmitting account.");
         }
     }
     else
     {
         throw new ArgumentException("You can only perform transactions that include your account as either the transmitter or receiver.");
     }
 }
Ejemplo n.º 6
0
 public void BuyPair(Kline kline, IPattern p, string name)/*Dictionary<string, PatternConfig> patternsConfig*/
 {
     if (Transactions.ContainsKey(kline.Symbol))
     {
         _logger.Info("Not Buying since we already baught it");
     }
     else
     {
         var time = Parser.ConvertTimeMsToDateTime(kline.CloseTime);
         var t    = new Transaction(kline.Symbol, kline.Close);
         t.StopLossConfig = GenerateStopLossObject(p);
         t.CalculateStopLoss(kline.Close);
         Transactions.Add(t.Symbol, t);
         var msg = String.Format("Trade: Buying {0} at {1}. Pattern: {2} Interval - {3}", t.Symbol, t.BuyPrice, p.Name, p.Interval);
         _logger.Email(string.Format("{0} Detected! Buy {1}", p.Name, t.Symbol), msg);
         if (FirstTransactionTime == DateTime.MinValue)
         {
             FirstTransactionTime = time;
         }
     }
 }
Ejemplo n.º 7
0
        internal static void Select001()
        {
            Transactions.Clear();

            SqlCommand readCmd = new SqlCommand("SELECT * FROM TRANSACTIONS", connection);

            try
            {
                SqlDataReader dataReader = readCmd.ExecuteReader();

                while (dataReader.Read())
                {
                    string img;

                    //Addes der til liste fra 1. kollone i TableName.
                    int      id          = dataReader.GetInt32(0);
                    double   amount      = dataReader.GetDouble(1);
                    DateTime date        = dataReader.GetDateTime(2);
                    string   description = dataReader.GetString(3);
                    int      subID       = dataReader.GetInt32(4);
                    if (dataReader.GetString(5) == null)
                    {
                        img = "https://n6-img-fp.akamaized.net/free-icon/businessman_318-72886.jpg?size=338c&ext=jpg";
                    }
                    else
                    {
                        img = dataReader.GetString(5);
                    }


                    Transactions.Add(new Transaction {
                        TransactionID = id, Amount = amount, Date = date, Description = description, SubCat = subID, Img = img
                    });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 8
0
        public OrderTrackingData(Dictionary <string, object> fields, Dictionary <string, string> nameLookup) : this(fields.GetString(OrderIDKey), nameLookup)
        {
            Description     = fields.GetString(DescriptionKey);
            Notes           = fields.GetString(NotesKey).Trim();
            OrderNote       = fields.GetString(OrderNoteKey).Trim();
            Personalization = fields.GetString(PersonalizationKey).Trim();
            Stage           = fields.GetString(StageKey);
            if (fields.GetString(DueDateKey) != "")
            {
                DueDate = DateTime.Parse(fields.GetString(DueDateKey));
            }
            if (fields.GetString(ShippedDateKey) != "")
            {
                ShipDate = DateTime.Parse(fields.GetString(ShippedDateKey));
            }
            Priority  = (fields.GetString(RushKey).ToLower() == "true");
            Cancelled = (fields.GetString(CancelledKey).ToLower() == "true");

            IsInventoryRequest  = (fields.GetString(InventoryRequestKey).ToLower() == "true");
            OrderType           = (fields.GetString(OrderTypeKey));
            PrintOperator       = GetNameFromIdIfPresent(fields.GetString(PrintOperatorKey), _NameLookup);
            DestinationLocation = GetNameFromIdIfPresent(fields.GetString(DestinationLocationKey), _NameLookup);
            Channel             = fields.GetString(ChannelKey);
            Shipper             = GetNameFromIdIfPresent(fields.GetString(ShipperKey), _NameLookup);
            ShipperPay          = NumberParseOrDefault(fields.GetString(ShipperPayKey));
            OrderURL            = fields.GetString(OrderURLKey);
            DesignerURL         = fields.GetString(DesignerURLKey);
            OrderValue          = NumberParseOrDefault(fields.GetString(OrderValueKey));
            RequestedQuantity   = (int)NumberParseOrDefault(fields.GetString(RequestedQuantityKey));
            // IncludedComponentId = fields.GetString(IncludedComponentIDKey);
            // IncludedItems - need to make this readable
            fields.TryGetValue("Transactions", out var transactionsObj);
            if (transactionsObj != null)
            {
                foreach (var txn in (JArray)(transactionsObj))
                {
                    Transactions.Add(txn.Value <string>());
                }
            }
        }
Ejemplo n.º 9
0
        public void ImportFromCSV(string fileName)
        {
            if (!File.Exists(fileName))
            {
                MessageBox.Show("File doesn't exist");
            }
            else
            {
                var  linesOfDocument = File.ReadAllLines(fileName, Encoding.GetEncoding("windows-1250"));
                bool isFirstLine     = true;
                foreach (var line in linesOfDocument)
                {
                    if (isFirstLine)
                    {
                        isFirstLine = false;
                        continue;
                    }
                    var splitLine = line.Split(';');
                    var date      = splitLine[0];
                    var amount    = splitLine[1];
                    var shopPlace = splitLine[2];
                    var category  = splitLine[3];

                    if (date == "" || amount == "")
                    {
                        return;
                    }

                    var tx = new TransactionRecord()
                    {
                        Amount        = float.Parse(amount),
                        Category      = category,
                        Date          = DateTime.Parse(date),
                        Description   = "",
                        ShoppingPlace = shopPlace
                    };
                    Transactions.Add(tx);
                }
            }
        }
        public void Add(DateTime dt, int payeeId, int recepientId, double amount)
        {
            if (recepientId == payeeId)
            {
                throw new ArgumentException("Recepient and payee must not be the same", nameof(recepientId));
            }
            var payee     = Users.GetExist(payeeId, "Payee");
            var recepient = Users.GetExist(recepientId, "Recepient");

            if (amount > payee.Balance)
            {
                throw new ArgumentException("Balance of payee less then amount", nameof(amount));
            }

            Transactions.Add(dt, payeeId, recepientId, amount);

            payee.Balance     -= amount;
            recepient.Balance += amount;

            Users.UpdateBalance(payee);
            Users.UpdateBalance(recepient);
        }
Ejemplo n.º 11
0
 public void AddBalance(string Guid, double money)
 {
     try
     {
         var carForAddMoney = Cars.Find(car => car.ID == Guid);
         if (carForAddMoney.Fine > 0)
         {
             Transaction transaction;
             carForAddMoney.PayFine(money, out transaction);
             Balance += transaction.Tax;
             Transactions.Add(transaction);
         }
         else
         {
             carForAddMoney.AddMoney(money);
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
Ejemplo n.º 12
0
 /// <summary>
 /// This handler handles the event when the <see cref="ITransactionRepository.SaveTransactionCompleted"/>
 /// event is raised by <see cref="_transactionRepository"/>.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void TransactionRepositorySaveTransactionCompleted(object sender, RepositoryTaskFinishedEventArgs e)
 {
     ThreadSafeInvoke(() =>
     {
         _messagingService.CloseProgressMessage();
         if (e.HasError)
         {
             _messagingService.ShowMessage(UIText.ERROR_OCCURED_MSG);
         }
         if (!Transactions.Contains(SelectedTransaction))
         {
             Transactions.Add(SelectedTransaction);
             if (null != SelectedTransaction)                     //Redundant but safe check
             {
                 SelectedTransaction.Refresh();
             }
             TotalIncome      = Transactions.Where(t => t.FlowType == TransactionFlowType.Income).Sum(t => t.Entity.Amount);
             TotalExpenditure = Transactions.Where(t => t.FlowType == TransactionFlowType.Expenditure).Sum(t => t.Entity.Amount);
             //  GraphItems = GetGraphData(Transactions.Select(t => t.Entity).ToList());
         }
     });
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Buy stocks
        /// </summary>
        /// <param name="companyName"></param>
        /// <param name="companySymbol"></param>
        /// <param name="currentSharePrice"></param>
        /// <param name="numOfShares"></param>
        /// <param name="time"></param>
        /// <returns></returns>
        public bool BuyStock(string companyName, string companySymbol, double currentSharePrice, int numOfShares, DateTime time)
        {
            if (!stock.IsOpenStockMarket() && EnforceMarketClosure)
            {
                MessageBox.Show("The market is closed.");
                return(false);
            }

            if (numOfShares * currentSharePrice > Cash)
            {
                MessageBox.Show("You don't have enough money for that purchase. Dummy.");
                return(false);
            }

            double transactionAmount = (numOfShares * currentSharePrice);
            // create a new holding if one doesn't already exist
            Holding holding = GetHolding(companySymbol);

            if (holding == null)
            {
                holding = new Holding(companySymbol);
                Holdings.Add(holding);
                holding.companyName       = companyName;
                holding.currentSharePrice = currentSharePrice;
            }
            holding.numOfShares   += numOfShares;
            holding.totalInvested += (transactionAmount);
            holding.worth         += (transactionAmount);

            // Add to list of transactions
            Transactions.Add(new Transaction(companyName, companySymbol, currentSharePrice, numOfShares, time));

            MessageBox.Show("You just purchased " + numOfShares + " shares of " + companyName + " stock at" + currentSharePrice.ToString("C2") + " per share.");
            Cash = Cash - transactionAmount;
            Cash = Cash - transactionFee;
            refresh();
            return(true);
        }
Ejemplo n.º 14
0
        private void UpdateTransactionList(IEnumerable <TransactionEntity> newTxs)
        {
            if (newTxs == null)
            {
                TransactionViewHeaderText = "No Transactions Found";
                return;
            }
            else if (newTxs.Any())
            {
                TransactionViewHeaderText = string.Empty;
            }

            var newTxAdded = false;

            foreach (var tx in newTxs)
            {
                if (!Transactions.Any(oldTx => string.Equals(oldTx.TxId, tx.TxId, StringComparison.Ordinal)))
                {
                    Transactions.Add(tx);
                    newTxAdded = true;
                }
                else
                {
                    var existingTxs = Transactions.Where(oldTx => string.Equals(oldTx.TxId, tx.TxId, StringComparison.Ordinal));
                    foreach (var existingTx in existingTxs)
                    {
                        existingTx.Confirmations = tx.Confirmations;
                    }
                }
            }

            if (newTxAdded)
            {
                Transactions = Transactions.OrderByDescending(tx => tx.TimeReceived).ToList();
            }

            RaisePropertyChanged("Transactions");
        }
            /// <summary>
            /// Enlists to transaction
            /// </summary>
            /// <param name="repository">enlisted repositary</param>
            /// <returns>transaction if any</returns>
            protected Transaction EnlistToTransaction(TestRepository <T> repository)
            {
                try
                {
                    var transaction = Transaction.Current;
                    if (transaction == null)
                    {
                        return(transaction);
                    }

                    TransactionalLock tlock;
                    TransactionData   value;

                    if (!Transactions.TryGetValue(transaction, out value))
                    {
                        tlock = new TransactionalLock();
                        Transactions.Add(transaction, new TransactionData()
                        {
                            CommitedSet = null, Locker = tlock
                        });
                    }
                    else
                    {
                        tlock = value.Locker;
                    }

                    tlock.Lock();
                    transaction.EnlistVolatile(repository, EnlistmentOptions.EnlistDuringPrepareRequired);
                    transaction.TransactionCompleted += repository.Transaction_TransactionCompleted;


                    return(transaction);
                }
                catch (InvalidOperationException exc)
                {
                    throw new System.Data.Entity.Core.EntityException("The underlying provider failed on open", exc);
                }
            }
Ejemplo n.º 16
0
        public void Charge(object obj)
        {
            if (obj as StateObjClass == null)
            {
                throw new Exception();
            }
            var StateObj = obj as StateObjClass;

            if (StateObj.TimerCanceled)
            // Dispose Requested.
            {
                StateObj.TimerReference.Dispose();
            }

            var payment = 0.0;

            if (StateObj.car.Balance < Settings.Price[StateObj.car.TypeCar])
            {
                payment = Settings.Price[StateObj.car.TypeCar] * Settings.Fine;
                StateObj.car.Balance -= payment;
            }
            else
            {
                payment = Settings.Price[StateObj.car.TypeCar];
                StateObj.car.Balance -= payment;
            }
            lock (locker)
            {
                Balance += payment;
                Transactions.Add(new Transaction
                {
                    TransactionTime = DateTime.Now,
                    CarId           = StateObj.car.Id,
                    Payment         = payment
                });
                //Console.WriteLine(Transactions.Last());
            }
        }
Ejemplo n.º 17
0
 private void Payment(object obj)
 {
     try
     {
         var car = obj as Car;
         var tax = CalculateTax(car);
         if (tax > car.Balance)
         {
             car.Fine += tax;
         }
         else
         {
             Transaction transaction;
             car.Pay(CalculateTax(car), out transaction);
             Balance += transaction.Tax;
             Transactions.Add(transaction);
         }
     }
     catch (Exception ex)
     {
         Logger.WriteException(ex.Message, "Parking.log");
     }
 }
Ejemplo n.º 18
0
        public void Withdraw(decimal amount, string comment)
        {
            Balance   -= amount;
            ModifyDate = DateTime.UtcNow;
            Transaction t = new Transaction
            {
                TransactionType = TransactionType.Withdrawal,
                Amount          = amount,
                ModifyDate      = DateTime.UtcNow,
                Comment         = comment
            };

            Transactions.Add(t);
            // deals with service fee
            if (t.ShouldCharge)
            {
                int nShouldCharge = Transactions.Where(x => x.ShouldCharge).Count();
                if (nShouldCharge > Transaction.NFreeTransaction)
                {
                    Transactions.Add(t.CreateServiceTransaction());
                }
            }
        }
Ejemplo n.º 19
0
        async Task ExecuteLoadItemsCommand()
        {
            IsBusy = true;

            try
            {
                Transactions.Clear();
                var items = await TransactionDataStore.GetItemsAsync(true);

                foreach (var item in items)
                {
                    Transactions.Add(item);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
Ejemplo n.º 20
0
        public void PayIn(decimal amount, TransactionType type, string source, decimal maximalDeposit)
        {
            if (UsedDepositThisMonth + amount > maximalDeposit)
            {
                throw new InvalidOperationException($"Transaction would exceed wallet ({Jmbg}) monthly deposit limit ({maximalDeposit} RSD).");
            }

            Balance += amount;

            if (LastTransactionDateTime.Month != DateTime.Now.Month || LastTransactionDateTime.Year != DateTime.Now.Year)
            {
                UsedDepositThisMonth  = 0M;
                UsedWithdrawThisMonth = 0M;
            }

            UsedDepositThisMonth += amount;

            var transaction = new Transaction(this, amount, type, source, Jmbg, Balance);

            Transactions.Add(transaction);

            LastTransactionDateTime = DateTime.Now;
        }
Ejemplo n.º 21
0
        public bool AddTransaction(Transaction transaction)
        {
            //process transaction and check if valid, unless block is genesis block then ignore.
            if (transaction == null)
            {
                return(false);
            }

            if ((PreviousHash != "0"))
            {
                if ((transaction.ProcessTransaction() != true))
                {
                    Console.WriteLine("Transaction failed to process. Discarded.");
                    return(false);
                }
            }

            Transactions.Add(transaction);

            Console.WriteLine("Transaction Successfully added to Block");

            return(true);
        }
Ejemplo n.º 22
0
        public void AddNewTransactions()
        {
            if (Device.RuntimePlatform == Device.macOS)
            {
                if (CategorySelected != null)
                {
                    var transaction = new TransactionDetail
                    {
                        Category = CategorySelected.ToString(),
                        Date     = Date,
                        Spent    = SpentOn,
                        Name     = ExpenseDescription
                    };

                    App.DataService.InsertTansaction(transaction);
                    Transactions.Add(transaction);
                    NavigationService.NavigatePopToRoot();
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(SingleTransaction.ExpenseDescription))
                {
                    var newTransaction = SingleTransaction;
                    var transaction    = new TransactionDetail
                    {
                        Category = newTransaction.Category.ToString(),
                        Date     = newTransaction.Date,
                        Spent    = newTransaction.Spent,
                        Name     = newTransaction.ExpenseDescription
                    };
                    App.DataService.InsertTansaction(transaction);
                    Transactions.Add(transaction);
                    NavigationService.NavigatePopToRoot();
                }
            }
        }
Ejemplo n.º 23
0
        private async void AddTransactionsView()
        {
            List <DBTransaction> _transactions = null;

            try
            {
                IsWalletPanelEnabled = false;
                _transactions        = await _serviceTransaction.GetWalletTransactionsAsync(WalletService.CurrentWallet.Guid);

                foreach (var tr in _transactions)
                {
                    Transactions.Add(new TransactionDetailsViewModel(tr, _serviceTransaction, _serviceWallet, _currentWallet, DeleteCurrentTransaction));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Transactions loading was failed: {ex.Message}");
                return;
            }
            finally
            {
                IsWalletPanelEnabled = true;
            }
        }
Ejemplo n.º 24
0
        public void PayIn(decimal amount, TransactionType transactionType, decimal maxDeposit)
        {
            if (UsedDepositForCurrentMonth + amount > maxDeposit)
            {
                throw new InvalidOperationException($"Transaction not allowed: Monthly deposit limit ({maxDeposit} RSD) would be exceeded.");
            }

            Balance += amount;

            if (LastTransactionDateTime.Month != DateTime.Now.Month ||
                LastTransactionDateTime.Year != DateTime.Now.Year)
            {
                UsedDepositForCurrentMonth    = 0m;
                UsedWithdrawalForCurrentMonth = 0m;
            }

            UsedDepositForCurrentMonth += amount;

            var transaction = new Transaction(amount, transactionType, this);

            Transactions.Add(transaction);

            LastTransactionDateTime = transaction.TransactionDateTime;
        }
Ejemplo n.º 25
0
 public ConfigurationTransaction this[string transactionName]
 {
     get
     {
         return(Transactions.First(tran => tran.TransactionName == transactionName).ConfigurationTransaction);
     }
     set
     {
         int index = Transactions.FindIndex(tran => tran.TransactionName == transactionName);
         if (index >= 0)
         {
             Transactions[index] = new PairHelper {
                 TransactionName = transactionName, ConfigurationTransaction = value
             }
         }
         ;
         else
         {
             Transactions.Add(new PairHelper {
                 TransactionName = transactionName, ConfigurationTransaction = value
             });
         }
     }
 }
Ejemplo n.º 26
0
        public async Task ExecuteLoadItemsCommand()
        {
            IsBusy = true;

            try
            {
                Transactions.Clear();
                var tx = await App.Database.GetTransactions();

                tx.Reverse();
                foreach (var t in tx)
                {
                    Transactions.Add(t);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
Ejemplo n.º 27
0
        //1x Weight Plate Ornament (SKU: WeightPlateOrnament_silver) -
        //$9.00 each

        private void InitializeShopifyOrderEmailTransactions(List <string> transactionEmailStrings)
        {
            foreach (string orderText in transactionEmailStrings)
            {
                var itemName          = Regex.Match(orderText + "\n", @"\d+x\s(.*?)[-(\r\n]").Groups[1]?.Value;
                var quantity          = Regex.Match(orderText, @"\d+").Value;
                var sku               = Regex.Match(orderText, @"\(SKU:\s*([^)]*)")?.Groups[1]?.Value;
                var setQuantityString = Regex.Match(orderText, @"\[(\d+)\]")?.Groups[1]?.Value;
                var setQuantity       = 1;

                if (!string.IsNullOrEmpty(setQuantityString))
                {
                    setQuantity = int.Parse(setQuantityString);
                }

                var transaction = new Transaction(sku: sku)
                {
                    ItemName = itemName,
                    Quantity = int.Parse(quantity) * setQuantity,
                };

                Transactions.Add(transaction);
            }
        }
Ejemplo n.º 28
0
        public void ShouldRaiseAnEventWithTheAddedTransactionAndTheSenderWhenAddingATransaction()
        {
            var       transactions = new Transactions();
            object    eventSender  = null;
            EventArgs eventArgs    = null;

            transactions.AddEvent += (sender, eventArgument) =>
            {
                eventSender = sender;
                eventArgs   = eventArgument;
            };

            uint     depositAmount = 10;
            DateTime today         = default;
            Deposit  deposit       = new Deposit(today, depositAmount);

            transactions.Add(deposit);

            Check.That(eventSender).IsEqualTo(transactions);
            Check.That(eventArgs).IsInstanceOf <TransactionEventArgs>();
            var transactionEventArgs = eventArgs as TransactionEventArgs;

            Check.That(transactionEventArgs.Transaction).IsEqualTo(deposit);
        }
Ejemplo n.º 29
0
 public Transaction AddTransaction(Transaction tx)
 {
     Transactions.Add(tx);
     return(tx);
 }
        public HsbcCreditStatement(string allLinesAsOne, string filePath = "Not Given", bool statementDateOnly = false)
        {
            var allLines = allLinesAsOne.Split('\n');

            Bank     = "HSBC";
            FilePath = filePath;

            var interest = 0.0;

            for (var i = 0; i < allLines.Length; i++)
            {
                var line = allLines[i];

                //Recognises the line to be a transaction and creates a new transaction object
                if (HsbcCreditTransaction.IsMatch(line))
                {
                    Transactions.Add(new HsbcCreditTransaction(line));
                }

                //Reads previous balance, rounding to 2d.p. from the summary
                else if (line.Contains("Previous Balance"))
                {
                    var amount = Regex.Replace(line.Substring(17), ",", string.Empty);
                    PreviousBalance = -Helper.GetCurrency(amount);
                }

                //Reads the new balance, rounding to 2d.p. from the summary
                else if (line.Contains("New Balance"))
                {
                    var amount = Regex.Replace(line.Substring(12), ",", string.Empty);
                    NewBalance = -Helper.GetCurrency(amount);
                }

                //Recognises the line to be a declaration of the statement date and that we haven't already assigned it
                else if (Regex.IsMatch(line, StatementDatePattern) && StatementDate == DateTime.MinValue)
                {
                    var matches = Regex.Match(line, StatementDatePattern);
                    StatementDate = DateTime.Parse(Helper.ConvertToShortDate(matches.Groups[1].ToString()));

                    if (statementDateOnly)
                    {
                        return;
                    }
                }

                //Recognises this is where the interest would be
                //but formatting means we sometimes have the actual amount on the previous line
                else if (Regex.IsMatch(line, "TOTAL INTEREST CHARGED ON THIS STATEMENT"))
                {
                    if (Regex.IsMatch(line, InterestPattern))
                    {
                        var matches = Regex.Match(line, InterestPattern);
                        interest = Helper.GetCurrency(matches.Groups[2].ToString());
                    }
                    else
                    {
                        interest = Helper.GetCurrency(allLines[i - 1]);
                    }
                }
            }

            if (interest != 0.0)
            {
                Transactions.Add(new HsbcCreditTransaction(StatementDate, interest));
            }

            Transactions = Transactions.OrderBy(t => t.DateReceivedByUs).ToList();
        }
        public override Transactions GetTransactions(long userId)
        {
            Transactions transactions = new Transactions();
            using (MySqlConnection conn = new MySqlConnection(GetConnectionString()))
            {
                using (MySqlCommand cmd = new MySqlCommand(QRY_GET_TRANSACTIONS_BY_USERID, conn))
                {
                    cmd.Parameters.Add("@user_id", MySqlDbType.Int64).Value = userId;

                    try
                    {
                        conn.Open();
                        using (MySqlDataReader rdr = cmd.ExecuteReader())
                        {
                            while (rdr.Read())
                            {
                                transactions.Add(new Transaction
                                {
                                    TransactionId = rdr.GetInt64(0),
                                    UserId = userId,
                                    Amount = rdr.GetDecimal(2),
                                    Date = rdr.GetDateTime(3),
                                    Description = rdr.GetString(4),
                                    ProductId = rdr.GetInt64(5),
                                    Status = rdr.GetString(6),
                                    StatusCode = rdr.GetString(7),
                                    Merchant = rdr.GetString(8),
                                    PaymentId = rdr.GetString(9),
                                    TransactionReference = rdr.GetString(10),
                                    PaymentMethod = rdr.GetString(11)
                                });
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.Write(LogLevel.Error, ex, "GetTransactions<Exception>");
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            return transactions;
        }