c++ – Exchange simulation that trades between currencies

I need help to optimise the code as it becomes slow with a large dataset. I have an exchange simulation program that takes in market prices from a csv and then allows the user to place bids and offers for the products (currencies) that are up for trade.

OrderBookEntry.cpp contains the constructors

#include "OrderBookEntry.h"

OrderBookEntry::OrderBookEntry( double _price, 
                        double _amount, 
                        std::string _timestamp, 
                        std::string _product, 
                        OrderBookType _orderType, 
                        std::string _username)
: price(_price), 
  amount(_amount), 
  timestamp(_timestamp),
  product(_product), 
  orderType(_orderType), 
  username(_username)
{
  
    
}

OrderBookType OrderBookEntry::stringToOrderBookType(std::string s)
{
  if (s == "ask")
  {
    return OrderBookType::ask;
  }
  if (s == "bid")
  {
    return OrderBookType::bid;
  }
  return OrderBookType::unknown;
}

OrderBook.cpp processes bids and offers

#include <map>
#include <algorithm>
#include <iostream>
#include "OrderBook.h"
#include "CSVReader.h"


/** construct, reading a csv data file */
/* R1A: Retrieve the live order book from the Merklerex exchange simulation */
OrderBook::OrderBook(std::string filename)
{
    orders = CSVReader::readCSV(filename);
}

/** return vector of all known products in the dataset*/
std::vector<std::string> OrderBook::getKnownProducts()
{
    std::vector<std::string> products;

    std::map<std::string,bool> prodMap;

    for (OrderBookEntry& e : orders)
    {
        prodMap(e.product) = true;
    }
    
    // now flatten the map to a vector of strings
    for (auto const& e : prodMap)
    {
        products.push_back(e.first);
    }

    return products;
}
/** return vector of Orders according to the sent filters*/
std::vector<OrderBookEntry> OrderBook::getOrders(OrderBookType type, 
                                                 std::string product, 
                                                 std::string timestamp)
{
    std::vector<OrderBookEntry> orders_sub;
    for (OrderBookEntry& e : orders)
    {
        if (e.orderType == type && 
            e.product == product && 
            e.timestamp == timestamp )
            {
                orders_sub.push_back(e);
            }
    }
    return orders_sub;
}

void OrderBook::insertOrder(OrderBookEntry& order)
{
    orders.push_back(order);
    std::sort(orders.begin(), orders.end(), OrderBookEntry::compareByTimestamp);
}

/* R2D: Using the live order book from the exchange, decide if it should withdraw its bids at any point in time */
/* R3D: Using the live order book from the exchange, decide if it should withdraw its offers at any point in time */
void OrderBook::withdrawOrder(std::string time)
{
    for (std::size_t i = orders.size() - 1; i < orders.size(); --i)
    {
        if(orders(i).timestamp == time && orders(i).username == "simuser")
        { 
            orders.erase(orders.begin() + i);
        }
    }
}

std::vector<OrderBookEntry> OrderBook::matchAsksToBids(std::string product, std::string timestamp)
{
// asks = orderbook.asks
    std::vector<OrderBookEntry> asks = getOrders(OrderBookType::ask, 
                                                 product, 
                                                 timestamp);
// bids = orderbook.bids
    std::vector<OrderBookEntry> bids = getOrders(OrderBookType::bid, 
                                                 product, 
                                                 timestamp);

    // sales = ()
    std::vector<OrderBookEntry> sales; 

    // I put in a little check to ensure we have bids and asks
    // to process.
    if (asks.size() == 0 || bids.size() == 0)
    {
        std::cout << " OrderBook::matchAsksToBids no bids or asks" << std::endl;
        return sales;
    }

    // sort asks lowest first
    std::sort(asks.begin(), asks.end(), OrderBookEntry::compareByPriceAsc);
    // sort bids highest first
    std::sort(bids.begin(), bids.end(), OrderBookEntry::compareByPriceDesc);
    // for ask in asks:
    std::cout << "max ask " << asks(asks.size()-1).price << std::endl;
    std::cout << "min ask " << asks(0).price << std::endl;
    std::cout << "max bid " << bids(0).price << std::endl;
    std::cout << "min bid " << bids(bids.size()-1).price << std::endl;
    
    for (OrderBookEntry& ask : asks)
    {
    //     for bid in bids:
        for (OrderBookEntry& bid : bids)
        {
    //         if bid.price >= ask.price # we have a match
            if (bid.price >= ask.price)
            {
    //             sale = new order()
    //             sale.price = ask.price
            OrderBookEntry sale{ask.price, 0, timestamp, 
                product, 
                OrderBookType::asksale};

                if (bid.username == "simuser")
                {
                    sale.username = "simuser";
                    sale.orderType = OrderBookType::bidsale;
                }
                if (ask.username == "simuser")
                {
                    sale.username = "simuser";
                    sale.orderType =  OrderBookType::asksale;
                }
            
    //             # now work out how much was sold and 
    //             # create new bids and asks covering 
    //             # anything that was not sold
    //             if bid.amount == ask.amount: # bid completely clears ask
                if (bid.amount == ask.amount)
                {
    //                 sale.amount = ask.amount
                    sale.amount = ask.amount;
    //                 sales.append(sale)
                    sales.push_back(sale);
    //                 bid.amount = 0 # make sure the bid is not processed again
                    bid.amount = 0;
    //                 # can do no more with this ask
    //                 # go onto the next ask
    //                 break
                    break;
                }
    //           if bid.amount > ask.amount:  # ask is completely gone slice the bid
                if (bid.amount > ask.amount)
                {
    //                 sale.amount = ask.amount
                    sale.amount = ask.amount;
    //                 sales.append(sale)
                    sales.push_back(sale);
    //                 # we adjust the bid in place
    //                 # so it can be used to process the next ask
    //                 bid.amount = bid.amount - ask.amount
                    bid.amount =  bid.amount - ask.amount;
    //                 # ask is completely gone, so go to next ask                
    //                 break
                    break;
                }


    //             if bid.amount < ask.amount # bid is completely gone, slice the ask
                if (bid.amount < ask.amount && 
                   bid.amount > 0)
                {
    //                 sale.amount = bid.amount
                    sale.amount = bid.amount;
    //                 sales.append(sale)
                    sales.push_back(sale);
    //                 # update the ask
    //                 # and allow further bids to process the remaining amount
    //                 ask.amount = ask.amount - bid.amount
                    ask.amount = ask.amount - bid.amount;
    //                 bid.amount = 0 # make sure the bid is not processed again
                    bid.amount = 0;
    //                 # some ask remains so go to the next bid
    //                 continue
                    continue;
                }
            }
        }
    }
    return sales;             
}

functions to place bids and asks in main

void MerkelMain::enterAsk()
{
    std::cout << "Make an ask - enter the amount: product, price, amount, eg. ETH/BTC,200,0.5" << std::endl;
    std::string input;
    std::getline(std::cin, input);

    std::vector<std::string> tokens = CSVReader::tokenise(input, ',');
    if (tokens.size() != 3)
    {
        std::cout << "MerkelMain::enterAsk Bad input! " << input << std::endl;
    }
    else {
        try {
            OrderBookEntry obe = CSVReader::stringsToOBE(
                tokens(1),
                tokens(2), 
                currentTime, 
                tokens(0), 
                OrderBookType::ask 
            );
            obe.username = "simuser";
            if (wallet.canFulfillOrder(obe))
            {
                std::cout << "Wallet looks good. " << std::endl;
                orderBook.insertOrder(obe);
            }
            else {
                std::cout << "Wallet has insufficient funds . " << std::endl;
            }
        }catch (const std::exception& e)
        {
            std::cout << " MerkelMain::enterAsk Bad input " << std::endl;
        }   
    }
}

void MerkelMain::enterBid()
{
    std::cout << "Make a bid - enter the amount: product, price, amount, eg. ETH/BTC,200,0.5" << std::endl;
    std::string input;
    std::getline(std::cin, input);

    std::vector<std::string> tokens = CSVReader::tokenise(input, ',');
    if (tokens.size() != 3)
    {
        std::cout << "MerkelMain::enterBid Bad input! " << input << std::endl;
    }
    else {
        try {
            OrderBookEntry obe = CSVReader::stringsToOBE(
                tokens(1),
                tokens(2), 
                currentTime, 
                tokens(0), 
                OrderBookType::bid 
            );
            obe.username = "simuser";

            if (wallet.canFulfillOrder(obe))
            {
                std::cout << "Wallet looks good. " << std::endl;
                orderBook.insertOrder(obe);
            }
            else {
                std::cout << "Wallet has insufficient funds . " << std::endl;
            }
        }catch (const std::exception& e)
        {
            std::cout << " MerkelMain::enterBid Bad input " << std::endl;
        }   
    }
}

CSVReader.cpp

#include <iostream>
#include <fstream>
#include "CSVReader.h"


CSVReader::CSVReader()
{

}

std::vector<OrderBookEntry> CSVReader::readCSV(std::string csvFilename)
{
    std::vector<OrderBookEntry> entries;

    std::ifstream csvFile{csvFilename};
    std::string line;
    if (csvFile.is_open())
    {
        while(std::getline(csvFile, line))
        {
            try {
                OrderBookEntry obe = stringsToOBE(tokenise(line, ','));
                entries.push_back(obe);
            }catch(const std::exception& e)
            {
                std::cout << "CSVReader::readCSV bad data"  << std::endl;
            }
        }// end of while
    }    

    std::cout << "CSVReader::readCSV read " << entries.size() << " entries"  << std::endl;
    return entries; 
}

std::vector<std::string> CSVReader::tokenise(std::string csvLine, char separator)
{
   std::vector<std::string> tokens;
   signed int start, end;
   std::string token;
    start = csvLine.find_first_not_of(separator, 0);
    do{
        end = csvLine.find_first_of(separator, start);
        if (start == csvLine.length() || start == end) break;
        if (end >= 0) token = csvLine.substr(start, end - start);
        else token = csvLine.substr(start, csvLine.length() - start);
        tokens.push_back(token);
    start = end + 1;
    }while(end > 0);

   return tokens; 
}

OrderBookEntry CSVReader::stringsToOBE(std::vector<std::string> tokens)
{
    double price, amount;

    if (tokens.size() != 5) // bad
    {
        std::cout << "Bad line " << std::endl;
        throw std::exception{};
    }
    // we have 5 tokens
    try {
         price = std::stod(tokens(3));
         amount = std::stod(tokens(4));
    }catch(const std::exception& e){
        std::cout << "CSVReader::stringsToOBE Bad float! " << tokens(3)<< std::endl;
        std::cout << "CSVReader::stringsToOBE Bad float! " << tokens(4)<< std::endl; 
        throw;        
    }

    OrderBookEntry obe{price, 
                        amount, 
                        tokens(0),
                        tokens(1), 
                        OrderBookEntry::stringToOrderBookType(tokens(2))};

    return obe; 
}


OrderBookEntry CSVReader::stringsToOBE(std::string priceString, 
                                    std::string amountString, 
                                    std::string timestamp, 
                                    std::string product, 
                                    OrderBookType orderType)
{
    double price, amount;
    try {
         price = std::stod(priceString);
         amount = std::stod(amountString);
    }catch(const std::exception& e){
        std::cout << "CSVReader::stringsToOBE Bad float! " << priceString<< std::endl;
        std::cout << "CSVReader::stringsToOBE Bad float! " << amountString<< std::endl; 
        throw;        
    }
    OrderBookEntry obe{price, 
                    amount, 
                    timestamp,
                    product, 
                    orderType};
                
    return obe;
}

Some data from the csv. 1st part is the date, 2nd part is the product, 3rd part is the OrderBookType (asks or bids), 4th part is the price and 5th part is the amount. When placing bids or asks, users do not need to enter the date but need to key in a value for everything else.

2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02187308,7.44564869
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02187307,3.467434
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02187305,6.85567013
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.0218732,1.
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02187163,0.03322569
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02187008,0.21
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02186299,0.1
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02186251,0.0091
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02186053,0.58
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02186052,0.05

currencies – How to recover Exodus wallet from a google back up

I had to factory reset my phone because it was hacked. In my panic I forgot to retrieve and note down the copy of my Exodus 12 word secret recovery code. When I redownloaded my exodus app, I thought it will ask me to login like most other app, but it doesn’t. It only wants the 12 word recovery phrase, which I don’t have. I have a google back up for my phone from before I did the factory reset.

My question is will my exodus details be stored in that back up? When I go to check my back up, all the other apps are there except for exodus, I am not sure why. will there be anywhere in my phone memory where this might have been stored. Is there any other way to recover my 12 word recovery phrase? I did login to my husband’s phone using my exodus login about 6 months ago, is there a way to retrieve that from my husband’s phone by going through historic data. I have the BTC address that I used to transfer the bitcoins to my exodus account. Will that help at all.

Any help or recommendations will be good. I have already contacted exodus but they haven’t been able to help.

My phone is ASUS Rog 2. Any help would be much appreciated.

Allowed Currencies only show DKK in backoffice

I need to know why is my magento 2 installation only show DKK as the currencies? and I also need to know how to add another currency in allowed currencies list such as USD and Euro
Text
any help would be greatly appreciated.
thanks

altcoin – If my service only accepts Bitcoin, will there be a lot of missed customers who only have non-Bitcoin crypto currencies?

I’m about to release a service which only takes payments in Bitcoin.

I’m wondering if this will impact me negatively in terms of not getting business from people who own other crypto currencies.

I don’t reject the others out of ideological reasons, but for practical ones:

  1. My hard disks are already overflowing from the 335.8 GB Bitcoin blockchain.
  2. I barely trust Bitcoin Core to run on my computer — I don’t trust non-Bitcoin clients whatsoever.
  3. Even if I did have the storage space and the trust, I would have to learn the respective RPC APIs (assuming they exist) for each “altcoin” as well. It took me a very long time to grasp the Bitcoin Core API.
  4. Any kind of reliance on a third-party service is unthinkable due to KYC/AML BS, as well as the obvious risk with getting my money stolen if somebody else “holds them for me”.

Is there any way around this? Is there some kind of mega-trusted “multi-coin” client which doesn’t need to download the entire blockchains, yet is able to securely and locally handle multiple of the biggest altcoins, so that I could support those for payments?

Or would anyone who has altcoins also have Bitcoin? I get the feeling that they are very, very few, but perhaps they are also more likely to spend their coins compared to the stubborn “HOLDers” of the increasingly valuable Bitcoin?

I know myself that I’m very unwilling to part from any of my Bitcoin, especially as the price is increasing… It’s just a fact for me, but I can’t speak for others. I don’t have any other crypto currencies myself, and the times I’ve looked into them, I’ve just been put off by their software. (In the cases where software even exists!)

Advice?

currencies – Could this ASIC-proof coin work?

I am thinking of starting an altcoin that everyone can use, which is associated with a network that everyone benefits from being a part of. For now, we will call it the Kokoro. Would this work?

The Kokoro

If there were a crypto-currency that the average person would benefit from mining it would take off in a heartbeat. If every person benefitted by putting their computer on the network, then most people would do so and this would usher in the wide adoption of said crypto. Frankly, this will be necessary if crypto is ever to replace fiat wholly (though this may not be everyone’s goal). The general premise behind the Kokoro is that anyone and everyone can mine it, and individuals are not outcompeted by costly mining rigs. Each address can only be receiving blocks from one miner at any given time.

The kokoro necessitates a decentralized ‘social media’ (such as AKASHA built on ethereum (1)), verified and acknowledged via ledger. The currency’s blockchain would tie each person’s public key to their ‘identity’, and mining hash rate is capped at a certain reasonable limit per identity. A working mechanism could be as follows: 10 verified identities must vouch that your identity is in fact real. If they vouch for a fake identity, they will be penalized. Each identity is allowed to be mining on only one device, and the hash rate is capped at a certain level. ‘Difficulty’ and ‘Rewards’ can be static variables, so people are simply ‘paid’ for their time of being part of the system. These rewards will be small compared to the cost of living, but not totally negligible (continuous mining may yield ~50USD/yr in 2020 price basket).

Contained in the kokoro’s network is a temporary smart contract (the genesis contract) by which people can trade in their fiat or crypto and receive kokoros (created at this time by the network). The value of the kokoro at this time will be fixed with respect to the USD via the immutable smart contract. The smart contract will take in information from oracles regarding other currency exchange rates to properly set the exchange rate with each other currency. This temporary smart contract serves as the mechanism for the first masse transfer of wealth from fiat to the kokoro. People will be incentivized to transfer their wealth during this short period as it will be the network’s largest growth period, corresponding to modest returns on investment following the expiration of the contract. Upon the contract’s expiration the value of the currency is left to market forces, and exchanging the currency is left to traditional currency exchanges, however, they will likely also utilize smart contracts because they’re more efficient than the traditional paper trail. Furthermore, these smart contracts will begin with similar terms when compared to the genesis contract, thus the price will at first track fiat currencies but it has the ability to stand on its own.

The kokoro is designed to facilitate the transition from fiat -> crypto in a realizable way. After the expiration of the genesis contract the idea is that every personal computer in the world will be using the kokoro blockchain. They will be benefitted by the network seeing it as free money by simply partaking at low energy costs, and their participation is the network.
The core concept of the kokoro is a mining rate that is limited per person so individuals will never be outmined by groups or stronger computers. Thus it encourages participation from all people and can sustain itself for the forseeable future.

Pros:

  1. Nullifies costly mining rigs.
  2. Incentivizes each and every person to participate.
  3. Eliminates mining pool and group efforts.
  4. Maximizes decentralization by maximizing the number of different users on the network and eliminating any incentive to hoard computing power.
  5. Minimizes transaction fees and times by having 10^7 – 10^9 computers on the global network
  6. Avoids massive inflationary periods that are unavoidable with traditional ICOs by starting with an initial kokoro-to-USD price fix in the genesis contract.
  7. The inflationary element is designed to be smaller than that of existing fiats, further incentivizing people to transfer their fiat into kokoros.
  8. Avoids major network transitions (i.e. what happens to bitcoin when the last bitcoin is mined)(and transition from PoW to PoS eth2.0), thus is a sustainable network when projected far into the future.
  9. Has minimal inflation that is linear with the number of users on the network, thus ultimately a function of the population.
  10. Capable of replacing fiat as the modus operandi, kicking off the crypto revolution.

Saudi Arabia And UAE Are Planning To Launch Digital Currencies

Saudi Arabia and UAE will launch their own digital currencies which are called CBDC and it’s approved by the central bank. Both the countries have decided to bring out a working CBDC since most other countries are also working on it. The CBDC project will be called "Aber" and they are currently running tests. Both Saudi Arabia and UAE relied on oil for generating revenue but that’s no longer true since new oil reserves have been found in the US. This is the reason why both the countries are…

Read more

currencies – Everchain White Label Wallet

Everchain White Label Wallet by EvercodeLab is a fully ready-made non-custodial crypto wallet with your brand’s logo.
Usage of this service allows you to send and receive tokens, view transaction history, have transaction fee control, it’s also has such features as balance in fiat currencies, ledger connection, usage of multiple addresses at the same time. Also, the design of wallet can be customised according to your brand logo and colour scheme. Development team can assume support service, but you also free to choose your own support team.
One of the examples is Atomic Wallet. It is a unique multi-cryptocurrency wallet. Guarantees maximum security and let users be anonymous during sessions, because it stores key on the user device only.
I recommend this service, because wallet’s clients personal safety is their greatest concern.

currencies – Current sentiment: Positive (Both stock market and bitcoin)…. Can you use bitcoin to invest in Stocks?

I was playing with the idea of enhancing portfolio risk/return characteristics. And one thing institutions do is hedge currency risk by investing in multiple different currency denominated assets. (Using complex solutions, swaps, derivatives, etc).
So. What exchanges if any allow you to use bitcoin / crytpto deposits to purchase stock market public equities or etf’s?
And wouldn’t this equate to bitcoin denominated ownership in Apple / MSFT / ADBE / KO / JNJ etc?

Stock market goes up – you win.
Bitcoin goes up – you win.

Thoughts? Advise?

❕NEWS – Six (6) Crypto currencies rich investors are buying. | Proxies123.com

Nairametrics revealed that aside bitcoin the rich Crypto Currency investors are adding coins mostly built on ethereum blockchain. The altcoins include Ethereum ETH,. LiNK, ELF, KNC and ZRX.
Are you guys familiar with these coins and does their Investment a push for you to also invest?

❓ASK – Jack ma said digital Currencies are the future | Proxies123.com

Jack Ma who is the founder the world largest e-commerce platform, Alibaba was reported by Bloomberg to have said at the Bund summit in Shanghai that the digital currency would play a vital a new global financial system.

However Jack ma was not specific about what he meant with digital currency but Binance CEO Zhao predicted it to be Crypto currencies while the Ethereum co-founder Buterin asked CZ Zhao what Ma meant by Digital currency and his reply was that “it is up to individuals interpretation”

What do you make of this?