Loop within PHP code that executes specific operations, such as a matching engine for orders

I am currently working on creating a simulated asset exchange platform using PHP. Let's consider the orderbook for a specific asset, XYZ:

| buy_price | amount | sell_price | amount |
|-----------|--------|------------|--------|
|  99.3     |  100   |  99.6      |  110   |
|  99.2     |  150   |  99.7      |  170   |
|  99.1     |  125   |  99.8      |  200   |

Now, if a user submits a buy order for 400 units at the market price, the orders will be filled accordingly:

110 units filled at 99.6
170 units filled at 99.7
120 units filled at 99.8

I need to create a conditional loop that iterates through open sell orders in order to fill the buy order of 400 units at various existing sell order prices listed in the orderbook. Additionally, I want to keep track of the executed trades and store them as arrays like:

$trade1 = ["amount" => 110, "price" => 99.6]
$trade2 = ["amount" => 170, "price" => 99.7]
$trade3 = ["amount" => 120, "price" => 99.8]

Answer №1

If you want to effectively keep track of the credits towards the buy order while looping through, consider using a single multi-dimensional array instead of multiple arrays. This way, you can store the executed trades more efficiently.

// Representation of ordered result from DB
$sellOrders = array(
    array("sell_price" => 99.6, "amount" => 110),
    array("sell_price" => 99.7, "amount" => 170),
    array("sell_price" => 99.8, "amount" => 200),
);

// Tracking total bought/sold
$purchasedCount = 0;
// Number of buy orders
$orderCount = 400;
// Array to store trade summaries
$trades = array();

foreach($sellOrders as $sell)
{
    $thisPurchase = 0;
    if($orderCount - $purchasedCount >= $sell['amount'])
    {
        $thisPurchase = $sell['amount'];
        $purchasedCount += $sell['amount'];
    }
    else
    {
        $thisPurchase = $orderCount - $purchasedCount;
        $purchasedCount = $orderCount;
    }

    $trades[] = array("amount" => $thisPurchase, "price" => $sell['sell_price']);

    if($purchasedCount == $orderCount)
    {
        break;
    }
}

var_dump($trades);

Check out the DEMO here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Rest assured, with Ajax Security, your protection is in good

I am currently developing a browser game that heavily utilizes AJAX instead of page refreshes. The combination of PHP and JavaScript is being employed for this project. However, during the course of my work, I became aware of the potential security vulnera ...

Toggle the image and update the corresponding value in the MySQL database upon clicking

Looking to implement a feature that allows users to bookmark pages in my PHP application using JavaScript. The concept involves having a list of items, each accompanied by an image (potentially an empty star). When a user clicks on the image, it will upda ...

Symfony ElasticaBundle event listener and method for building queries

I want to upload leads in elastic only when their status is approved. Here is my mapping: persistence: driver: orm model: Artel\ProfileBundle\Entity\Lead provider: query_builder_method: createIsActiveQueryBuilder lis ...

Determining if a URL is a subdomain URL using PHP

I created a function to check whether a URL is a subdomain URL or not. <?php header("Content-Type: text/plain"); function checkSubDomain($url) { $url = parse_url($url)["host"]; if(strstr($url,'.',true)=='www') { ...

Show the Best Deals on Category Pages Using Woocommerce

On my quest to showcase the lowest price on category pages instead of a price range, while still displaying the range on individual product pages, I stumbled upon a solution shared by another user: add_filter('woocommerce_variable_price_html', & ...

Encountering an issue with the Ionic Serve Command

Currently, I am working on creating a mobile app with the Ionic framework. After running the command ionic server, I encountered this error: /deps/uv/src/unix/stream.c:494: uv__server_io: Assertion `events == 1' failed Any suggestions or assistanc ...

Can anyone provide assistance with formatting arrays?

I am working with two arrays where I need to compare elements and populate a new array based on certain conditions. Array1: $days contains a list of dates. $days = Array ( [0] => 2012-06-23 [1] => 2012-06-24 [2] = ...

Edit the information within an element

Seeking assistance in swapping out text within anchor tags (<a>here</a>) on a website built with Wordpress. Unable to alter the HTML directly, so looking to use Jquery or PHP. The challenge lies in the lack of classes or IDs for the anchor tag ...

What is the proper method for submitting a mail form via AJAX without using jQuery?

Currently, I am working on integrating a PHP mail form with AJAX. The aim is to create a straightforward form that collects user information such as phone numbers and sends it to my email address. While I have managed to set up the form to send emails usi ...

``Please proceed with the form submission only if it has been verified and

Within my web application, there are several pages that handle submitted data from forms. I would like to prevent the following scenario: A user creates a form on the client side with identical fields to my original form and sends it to the URL responsibl ...

Launch a dialogue box by clicking on the buttons corresponding to the article ID

I am currently in the process of setting up an admin panel with some quick actions for managing my articles, such as deleting them. When I click on the trash can icon, a dialog box should open and prompt me to confirm the deletion. This dialog box should b ...

How should a function be called within a string while adhering to proper syntax?

Why do I keep encountering an error stating that the function name must be in a string? Or in some cases, it just runs without printing anything. What could I be overlooking? <?php $funName = "{'$oneRun()'}"; echo "Hello! You are currently e ...

"Encountering a 500 internal server error while working with

Currently, I have set up an ajax functionality with two different contents retrieved from separate files. Files: my_site_id_one.php: <div class="id_one_content"> <?php echo do_shortcode('[shortcode_one]'); ?> </div> my_ ...

Issue with jQuery function not recognizing escaped double quotes in PHP script

Greetings! I am currently utilizing a custom control with PHP code. $parentLinkCombo = '<select name="ParentComboLink" onchange="changeChildCombo(\"LICENCE\");" id="ParentComboLink" >'; In order to handle the onchange event, I ...

Executing CMD commands in PHP using exec or system functions

I attempted to execute cmd commands and system functions using PHP code, but I am not receiving any output. Should I adjust settings in the php.ini file to enable this feature? ...

Here is a helpful guide on updating dropdown values in real time by retrieving data from an SQL database

This feature allows users to select a package category from a dropdown menu. For example, selecting "Unifi" will display only Unifi packages, while selecting "Streamyx" will show only Streamyx packages. However, if I first select Unifi and then change to S ...

Tips on serializing two arrays into JSON format and incorporating them in an AJAX request

I have a task where I need to retrieve all the names and details associated with a specific reference number. To accomplish this, I am using a while loop. However, I am unsure of how to encode these values in JSON format so that I can use them in AJAX for ...

In PHP, subclassing classes

In my application, I am utilizing a Salesforce class called SforceEnterpriseClient in various sections. I am interested in extending this class to enhance its functionality, particularly to enable it to return a single array from a record set that is curre ...

Accessing information from the database when logging in

I am currently working on a mobile application using Slim and Ajax. Within my database, there is a column that stores session codes for logins. After a user logs in, I need to compare the entered username with the database and retrieve the sessionCode asso ...

Is mysql(i)_real_escape_string a reliable method for ensuring data safety?

function CustomQuery() { $arguments = func_get_args (); if (sizeof ($arguments) > 0) { $query_string = $arguments[0]; for ($index = 1; $index < sizeof ($arguments); $index++) $query_string = preg_replac ...