Dynamic pricing and algorithmic marketing: the complete technical playbook

TL;DR

Difficulty: Advanced

Run pricing and advertising as one nightly loop. Read your own sales, stock and costs and competitors' public prices, propose a price per product from strategy, stock and elasticity, cap every move, and log the reason. Use the markup rule only where a real elasticity estimate is below minus one. Judge ads by profit on ad spend, not ROAS, and split budget by margin, conversion, stock and price position. Price products, never people: no protected grounds, no data without consent. Any price reduction must show the lowest price of the previous 30 days. Use public data only, never coordinate with rivals.

Most shops set a price once, set an ad budget separately, and adjust both by hand once a month. This playbook builds the alternative in a Ruby on Rails shop on Solidus: a nightly loop that prices each product from its cost, stock, elasticity and competitors' public prices, inside limits a person sets, and moves ad spend towards profit. It covers the economics with corrected worked examples for an invented Cork cookware shop, the Irish and EU law on price reductions, personal prices and algorithmic collusion, and the code.

Most shops set a price once and then advertise against it

Here is how pricing and advertising run in most online shops. Someone sets a price when the product goes live. Someone else sets an advertising budget. The campaigns run, a dashboard fills up, and once a month somebody adjusts a few numbers by hand. Price, stock, margin and ad spend are decided by different people at different times, and none of them can see the others.

The alternative is a loop. Every night the shop reads its own sales, stock and costs, and the public prices of the competitors it actually meets. It works out a price for each product inside limits a person has set, writes that price into the shop and the product feed, and moves the advertising budget towards the products that earn the most profit, not the most revenue. Then it measures what happened and does it again.

This article is the playbook for building that loop in a Ruby on Rails shop on Solidus: the economics, the formulas, the law that decides what the loop may do in Ireland, and the code. It is a rewrite. The first version had a worked example whose numbers did not add up, a pricing formula that breaks for some products, a hook for charging individual customers different prices, and no word on the law. All four are fixed below, and I say where.

To keep the numbers concrete I use an invented shop. Lee Valley Cookware sells cast iron casseroles, knife sets and pans from a unit in Cork, at leevalleycookware.example. Nobody real, every number made up.

Why one price leaves money on the table

Different customers will pay different amounts for the same product. Economists call charging them different prices price discrimination, and they usually sort it into three degrees. First degree means charging each person exactly what they would pay at most. Second degree means offering versions, bundles or quantity breaks and letting each customer choose: buy two and save, the gift edition or the plain one. Third degree means charging different prices to groups you can see from the outside, such as students, trade customers or a different country.

The first version of this article said dynamic pricing "increasingly" approaches first degree by reading behavioural signals about each customer. I have taken that out of the engine. This playbook prices products, editions, channels and moments, never individual people. The legal reasons are further down, and there is a commercial one too: customers who find out they paid more than their neighbour for the same casserole do not come back.

Worked example: two groups of buyers, one casserole

Lee Valley's 24cm casserole costs €20 to buy in, pack and ship. Suppose there are two groups of buyers. Four hundred people would pay up to €50 (they are buying a present). Six hundred would pay up to €35 (they are buying for their own kitchen).

With one price for everyone, Lee Valley has to choose. At €50 only the gift buyers buy, so profit is (50−20)×400=12,000(50 - 20) \times 400 = 12{,}000, or €12,000. At €35 everybody buys, so profit is (35−20)×1,000=15,000(35 - 20) \times 1{,}000 = 15{,}000, or €15,000. At €40, a price that looks like a sensible compromise, only the gift buyers buy and profit falls to (40−20)×400=8,000(40 - 20) \times 400 = 8{,}000, or €8,000.

The old version of this example said the shop sold 1,000 casseroles at €40 and then, two lines later, that the €35 group would not buy at €40. Both cannot be true, so its "5% more profit" was wrong.

Now give the gift buyers their own edition: the same casserole in a printed box with a recipe card, at €50. The box and card cost €2, so each gift edition earns 50−22=2850 - 22 = 28 pounds. If the groups sort themselves cleanly, profit is 28×400+15×600=11,200+9,000=20,20028 \times 400 + 15 \times 600 = 11{,}200 + 9{,}000 = 20{,}200, or €20,200. That is about 35% more than the best single price.

Profit in pounds for one price of 40, one price of 50, one price of 35, and two editions at 50 and 35. Two editions earn the most at 20,200 pounds. Tap or click to open full screen and move around

The words "if the groups sort themselves cleanly" carry the whole example. Some gift buyers will buy the plain casserole and wrap it themselves. Designing editions, bundles and timing so that the groups really do separate is the hard part of second degree pricing, and it is a product decision before it is an algorithm.

Elasticity is the number the engine needs

The engine cannot know what each person would pay. It can know, roughly, how sales of each product respond when the price moves. That is the price elasticity of demand, defined in the Foundations:

ε=%ΔQ%ΔP\varepsilon = \frac{\%\Delta Q}{\%\Delta P}

ε\varepsilon is the elasticity, %ΔQ\%\Delta Q is the percentage change in the quantity sold and %ΔP\%\Delta P is the percentage change in price. An elasticity of −2-2 means a 10% price rise loses about 20% of unit sales. An elasticity of −0.5-0.5 means the same rise loses only about 5%.

If the elasticity is roughly constant around the current price, there is a simple rule for the price that maximises profit, the markup rule:1

P−CP=−1ε⟹P∗=C ε1+ε\frac{P - C}{P} = -\frac{1}{\varepsilon} \qquad\Longrightarrow\qquad P^{*} = \frac{C \, \varepsilon}{1 + \varepsilon}

PP is the price, CC is the marginal cost of one more unit (purchase price plus packaging, payment fees and any delivery you subsidise, not an average that includes rent), ε\varepsilon is the elasticity and P∗P^{*} is the profit maximising price. The left side, (P−C)/P(P - C)/P, is the margin as a share of the price. The rule only holds where demand is elastic, which means ε<−1\varepsilon < -1. The full derivation, and how to estimate ε\varepsilon from your own order history with a regression, is in modelling demand and price elasticity with regression, and the Foundations entry on elasticity covers the definition.

Worked example: the markup rule on the casserole

With C=20C = 20 and ε=−2\varepsilon = -2, the rule gives P∗=20×(−2)1−2=−40−1=40P^{*} = \frac{20 \times (-2)}{1 - 2} = \frac{-40}{-1} = 40, so €40. With ε=−4\varepsilon = -4, a much more price sensitive product, it gives P∗=−80−3=26.67P^{*} = \frac{-80}{-3} = 26.67, so €26.67.

Two warnings follow from the same formula, and the first version of this article missed both. With ε=−1.5\varepsilon = -1.5 the rule says P∗=−30−0.5=60P^{*} = \frac{-30}{-0.5} = 60, so €60. Moving the estimate from −2-2 to −1.5-1.5, well inside the error range of most real estimates, moves the "optimal" price by half. And with ε=−0.8\varepsilon = -0.8 the rule gives −160.2=−80\frac{-16}{0.2} = -80, a negative price. That is not a bug in the arithmetic. It means demand at today's price is inelastic, a price rise would increase profit, and the rule cannot say by how much because the assumption behind it does not hold there. The old code fed every product through this formula with a default elasticity of −2-2 when none was known. The new code below only uses the rule when there is a real estimate below −1-1, blends it with the current price instead of jumping to it, and caps every move.

Passive and active marketing, side by side

In the passive model, a change takes weeks to show up: you move something, wait for data, argue about what it means, and move something else. In the active model the shop runs the same loop every night with limits a person has set, and a person reviews the log rather than every price.

Tap or click to open full screen and move around

Nightly is deliberate. The old version ran every hour. Prices that move every hour are hard to explain to a customer, they get out of step with the price Google has crawled from your page, and, as the section on the law below shows, they make every "was" price you ever show look suspicious.

Competitor prices: collect them politely, use them alone

You cannot price sensibly without knowing what the shops you actually compete with charge. A competitor monitor does four things: it fetches competitors' public product pages on a schedule, matches their products to yours (by barcode number, GTIN, where both sides publish it, otherwise by a mapping a person has checked), stores the history, and flags significant changes.

How you collect matters as much as what you collect. Public pages only, no logins, an honest user agent with a contact address, robots.txt respected, a polite rate, and if a site blocks you, you stop. The legal reasons, from the database right to the Ryanair cases, are in competitor price monitoring in the EU: what is actually legal.

Tap or click to open full screen and move around

Once you have the data, each product gets a strategy. Undercut the lowest competitor by a fixed amount, for commodity products where you have a cost advantage. Match the market average, where price is not what you compete on. Hold a set premium, where brand, service or quality earn it. Or switch between them by stock: undercut when you are overstocked, hold a premium when stock is short, match otherwise. The strategies sit side by side in one catalogue. Lee Valley undercuts on a basic frying pan that every shop sells, matches on knife sets, and holds a premium on its own casserole colours.

Two rules apply to every strategy. The engine never goes below a floor of cost plus a minimum margin, whatever a competitor does. And competitor prices are one input among several, not a command. An engine that only ever follows the cheapest rival hands its pricing to that rival, and two engines that only follow each other can drift into exactly the pattern competition law worries about, which is covered below.

Margin aware advertising: spend where the profit is

Most ad accounts are judged by return on ad spend (ROAS): revenue from the ads divided by what the ads cost. Revenue is the wrong thing to divide.

Take two Lee Valley products, both sold at €100. The knife block costs €80, so its gross margin is 20%. The casserole set costs €40, so its margin is 60%. If both convert at the same rate for the same cost per click, their ROAS is identical, yet the casserole set earns three times the gross profit per sale. The measure that sees the difference is profit on ad spend (POAS):

POAS=R−COGSS=ROAS×m\text{POAS} = \frac{R - \text{COGS}}{S} = \text{ROAS} \times m

RR is the revenue the ads brought in, COGS\text{COGS} is the cost of the goods sold in those orders, SS is the ad spend and mm is the gross margin as a fraction of revenue, so ROAS=R/S\text{ROAS} = R/S. This is a ratio of two flows over the same period, explained under ratios and rates in the Foundations. A POAS above 1 means the gross profit from the ads covers their cost, before any other variable costs.

Worked through: a campaign with a ROAS of 4 on 20% margin products has POAS=4×0.2=0.8\text{POAS} = 4 \times 0.2 = 0.8. It loses 20 cent of gross profit on every pound spent, while its dashboard shows a healthy 4. A campaign with a ROAS of 2 on 60% margin products has POAS=2×0.6=1.2\text{POAS} = 2 \times 0.6 = 1.2, and it is the one making money.

Splitting a budget by score

The simplest margin aware allocation gives each product a score and splits the budget in proportion:

wi=si∑jsj,si=mi×ci×fistock×ficompw_i = \frac{s_i}{\sum_j s_j}, \qquad s_i = m_i \times c_i \times f_i^{\text{stock}} \times f_i^{\text{comp}}

wiw_i is product ii's share of the budget, sis_i its score and ∑jsj\sum_j s_j the sum of all scores. mim_i is the gross margin as a fraction, cic_i the conversion rate from ad clicks over the last 30 days, fistockf_i^{\text{stock}} a stock factor and ficompf_i^{\text{comp}} a competitive factor. Each share is a simple proportion, as in percentages in the Foundations. The stock factor I start with is 1.5 when there are more than eight weeks of stock, 1.3 for four to eight weeks, 1.0 for two to four, 0.8 for one to two and 0.5 under one week. The competitive factor is 1.2 when you are at or below the cheapest competitor, 1.0 near the market average and 0.7 when you are the most expensive.

Worked example: €3,000 across three products

Lee Valley spends €3,000 a month on Google Shopping across three products. The casserole has a margin of 50%, converts at 3.0%, has six weeks of stock (factor 1.3) and sits at the market average (1.0), so its score is 0.5×0.03×1.3×1.0=0.01950.5 \times 0.03 \times 1.3 \times 1.0 = 0.0195. The knife set has a margin of 35%, converts at 2.0%, has normal stock (1.0) and has the lowest price in the market (1.2), so 0.35×0.02×1.0×1.2=0.00840.35 \times 0.02 \times 1.0 \times 1.2 = 0.0084. The frying pan has a margin of 20%, converts at 4.5%, has under a week of stock (0.5) and is the most expensive (0.7), so 0.2×0.045×0.5×0.7=0.003150.2 \times 0.045 \times 0.5 \times 0.7 = 0.00315.

The scores add up to 0.0195+0.0084+0.00315=0.031050.0195 + 0.0084 + 0.00315 = 0.03105. The casserole gets 0.0195/0.03105=62.8%0.0195 / 0.03105 = 62.8\% of the budget, €1,884. The knife set gets 27.1%27.1\%, €812. The pan gets 10.1%10.1\%, €304. The pan converts best of the three, and a revenue optimiser would feed it. Here it gets the least, because it earns little per sale, it is about to sell out and a competitor undercuts it.

A score is a starting point, not an optimum. Ad spend has diminishing returns: the first €300 on the pan buys the most eager searchers, the next €300 buys less eager ones. The split that maximises profit is the one where the last pound on every product earns the same extra profit, which is the difference between marginal and average returns. A score cannot see that. So I treat the score as the first allocation, move budget in small steps, and keep a product's share only where the extra spend kept earning.

The law decides what the engine may do

Consumer law does not ban dynamic pricing. EU law treats prices that move with market demand as ordinary, and asks for extra information only when a price is personalised for the individual on the basis of automated decision making.2 In Ireland the rules on misleading and prohibited commercial practices sit in Part 3 of the Consumer Protection Act 2007, as amended by the Consumer Rights Act 2022, and the Competition and Consumer Protection Commission (CCPC) enforces them. I am not a solicitor and this is not legal advice. This is the map I build to, and a shop with an unusual model should take it to a solicitor.

Telling customers that prices move

A commercial practice is misleading under the 2007 Act if it gives false information, or information likely to deceive the average consumer, about matters including the price or the way it is calculated, and so leads them to a decision they would not otherwise have made.3 The list of practices banned outright includes falsely claiming that a product is available only for a limited time, or on particular terms for a limited time, to rush a decision.4

For the engine that means: a plain line on the product page or the delivery and pricing page that prices change with demand and stock; no countdown next to a price that is not about to change; and a basket freeze, so a variant sitting in an order that has reached payment is not repriced until the order completes or is abandoned.

"Was" prices and the 30 day rule

Ireland has a hard rule here, from the EU. The Omnibus Directive inserted Article 6a into the Price Indication Directive: any announcement of a price reduction must show the prior price, the lowest price the trader applied in at least the 30 days before the reduction.2 Ireland transposed it in 2022 as a new Regulation 5A of the European Communities (Requirements to Indicate Product Prices) Regulations 2002. A trader who announces a reduction must show the prior price, the prior price is the lowest price applied in the 30 days before the reduction (or before the first of several consecutive reductions), and a breach is an offence.5 The CCPC adds that any discount, an amount or a percentage off, must be based on that prior price, and that the rules apply in every sales channel, in store and online.6 The Court of Justice confirmed in 2024 that a percentage discount, or a promotional claim that a price is a bargain, must be calculated from the prior price.7

A dynamic pricing engine moves prices up and down by design, which makes this rule bite. Say the engine lowered the casserole from €40 to €36 for a week of high stock two weeks ago, and now you launch a sale at €32. The prior price is €36, not €40, so the honest reduction is 11%, not 20%. My rule therefore is: prices the engine moves are shown as plain prices, never as reductions. A strike through price appears only for a deliberate promotion, and the prior price shown is calculated from the price log, which is exactly what the lowest_before method below does.

Personal prices: the line I do not cross

Personalised pricing means showing different people different prices for the same product based on what is known about them. Before a consumer is bound by a distance contract, the Consumer Rights Act 2022 requires the trader to say, where applicable, that the price was personalised on the basis of automated decision making.8 The GDPR adds that a person has the right not to be subject to a decision based solely on automated processing that has legal or similarly significant effects, apart from narrow exceptions, and where an exception applies the business must provide at least human intervention, a way to express a view and a way to contest the decision.9 The Data Protection Commission (DPC) enforces that side.

Three rules follow, and they are not negotiable in anything I build. First, the engine never takes a protected ground as an input, nor a stand in for one: the Equal Status Act 2000 says a person must not discriminate in disposing of goods or providing a service to the public, on grounds such as gender, age, disability, race or membership of the Traveller community.10 Eircode, first name or device type can all act as a proxy. Openly advertised concessions, such as a student discount, are a deliberate business decision with their own legal check, not something an algorithm should discover. Second, the engine never uses personal data that was collected without a lawful basis, and never uses browsing data from cookies or similar technologies that needed consent the visitor did not give.11 Third, the engine prices products, editions, channels and moments, so neither the disclosure duty nor the GDPR question arises. The price_for_user hook from the first version of this code is gone.

Algorithmic collusion: react to the market, never coordinate with it

Reacting on your own to the prices your rivals publish is the competition the law wants. Section 4 of the Competition Act 2002 prohibits agreements and concerted practices that directly or indirectly fix selling prices, and Article 101 of the Treaty on the Functioning of the European Union (TFEU) says the same wherever trade between member states is affected.12 Software does not change that. The European Commission's guidelines say that using publicly available data to feed pricing software is legal, but an algorithm that carries out an agreement between competitors is collusion by code, and firms cannot escape liability because a machine set the price. They also describe hub and spoke, where sensitive information passes between competitors through a third party, such as a pricing tool from one IT company that rivals all use.13 The CCPC lists the penalties for price fixing as up to 10 years in prison and fines of up to €50 million or 20% of turnover.14

Research adds autonomous tacit collusion. In a simulated market, pricing agents based on Q learning learned to sustain prices above the competitive level and to punish a rival who cut.15 That was a laboratory result, not a finding against a real shop, but it is the reason for three design rules. The engine reads only the shop's own data and competitors' public prices. If you buy a repricing service, ask in writing whether its recommendations use any other client's non public data. And every price in the log carries a reason a person can read in terms of the shop's own costs, stock and strategy, never in terms of what a competitor is expected to do next.

The Solidus implementation

Now the code. It assumes a Solidus store on a recent Rails, a crawler that already follows the rules above and stores what it finds, and API access to Google Ads and Meta. It is a working skeleton, not a drop in gem: the class names are mine, and you will adapt the strategies, factors and limits to your catalogue.

Tables: competitor prices and a price log

Two tables. One holds the latest public price per competitor and variant. The other is the price log: every price the shop has charged, with the reason and the inputs. The log is your evidence for any reference price, your training data for the next elasticity estimate, and your answer when a customer or a regulator asks why a price moved.

# db/migrate/20260806000001_create_pricing_tables.rb
class CreatePricingTables < ActiveRecord::Migration[7.2]
  def change
    create_table :competitor_prices do |t|
      t.references :variant, null: false, foreign_key: { to_table: :spree_variants }
      t.string :competitor_domain, null: false
      t.decimal :price, precision: 10, scale: 2, null: false
      t.decimal :shipping_cost, precision: 10, scale: 2, null: false, default: 0
      t.boolean :in_stock, null: false, default: true
      t.datetime :seen_at, null: false
      t.timestamps
    end
    add_index :competitor_prices, [:variant_id, :competitor_domain], unique: true

    create_table :price_changes do |t|
      t.references :variant, null: false, foreign_key: { to_table: :spree_variants }
      t.string :currency, null: false
      t.decimal :old_amount, precision: 10, scale: 2
      t.decimal :new_amount, precision: 10, scale: 2, null: false
      t.string :reason, null: false
      t.jsonb :inputs, null: false, default: {}
      t.timestamps
    end
    add_index :price_changes, [:variant_id, :currency, :created_at]
  end
end
# app/models/competitor_price.rb
class CompetitorPrice < ApplicationRecord
  belongs_to :variant, class_name: "Spree::Variant"

  scope :fresh, -> { where(seen_at: 36.hours.ago..) }
  scope :in_stock, -> { where(in_stock: true) }

  def total_price
    price + shipping_cost
  end

  def self.for_variant(variant)
    fresh.in_stock.where(variant: variant)
  end

  def self.lowest_total(variant)
    for_variant(variant).map(&:total_price).min
  end

  def self.average_total(variant)
    totals = for_variant(variant).map(&:total_price)
    totals.empty? ? nil : totals.sum / totals.size
  end
end
# app/models/price_change.rb
class PriceChange < ApplicationRecord
  belongs_to :variant, class_name: "Spree::Variant"

  # Lowest price charged in the `days` before `at`, including the price that was
  # already in force when the window opened. This is the prior price a price
  # reduction must show under Regulation 5A of the Irish price indication rules.
  def self.lowest_before(variant, at:, currency: "EUR", days: 30)
    scope = where(variant: variant, currency: currency)
    window_start = at - days.days
    in_window = scope.where(created_at: window_start..at).minimum(:new_amount)
    in_force = scope.where(created_at: ...window_start).order(created_at: :desc).pick(:new_amount)
    [in_window, in_force].compact.min
  end
end

Syncing competitor prices

The sync job reads from your crawler's own store. Matching is the step that goes wrong most often, so it relies on a mapping table that a person has confirmed, filled first by GTIN where both shops publish one. The first version looked competitor barcodes up in the Solidus sku column, which only works if your SKUs happen to be barcodes.

# app/jobs/competitor_price_sync_job.rb
class CompetitorPriceSyncJob < ApplicationJob
  queue_as :default

  def perform
    CrawlerStore.observations_since(26.hours.ago).each do |obs|
      mapping = CompetitorProductMapping.confirmed.find_by(
        competitor_domain: obs.domain, competitor_url: obs.url
      )
      next unless mapping

      CompetitorPrice.upsert(
        {
          variant_id: mapping.variant_id,
          competitor_domain: obs.domain,
          price: obs.price,
          shipping_cost: obs.shipping_cost || 0,
          in_stock: obs.in_stock,
          seen_at: obs.fetched_at,
          created_at: Time.current,
          updated_at: Time.current
        },
        unique_by: [:variant_id, :competitor_domain]
      )
    end
  end
end

The pricing engine

The engine proposes, it does not decide alone. Its inputs are the variant's cost, stock, the competitors' public prices and the product's elasticity estimate. Nothing about the customer goes in.

# app/services/pricing_engine.rb
class PricingEngine
  Proposal = Struct.new(:amount, :reason, :inputs, :needs_review, keyword_init: true)

  MAX_STEP = 0.05          # never move more than 5% in one run
  ELASTICITY_WEIGHT = 0.3  # how far to lean towards the markup rule each run

  def initialize(variant, currency: "EUR")
    @variant = variant
    @product = variant.product
    @currency = currency
    @config = PricingConfig.for(@product)
  end

  def propose
    return nil if in_checkout?
    cost = @variant.cost_price
    return nil unless cost && current_price

    target = strategy_price
    target = lean_towards_markup_rule(target, cost)
    target *= stock_adjustment
    capped = target.clamp(current_price * (1 - MAX_STEP), current_price * (1 + MAX_STEP))
    final = capped.clamp(floor(cost), ceiling).round(2)

    Proposal.new(
      amount: final,
      reason: "#{@config.strategy}, #{weeks_of_stock.round(1)} weeks of stock",
      inputs: inputs(cost),
      needs_review: final == floor(cost) || final == ceiling
    )
  end

  private

  def current_price
    @current_price ||= @variant.price_for_options(pricing_options)&.amount
  end

  def pricing_options
    Spree::Config.pricing_options_class.new(currency: @currency)
  end

  def strategy_price
    lowest = CompetitorPrice.lowest_total(@variant)
    average = CompetitorPrice.average_total(@variant)

    case effective_strategy
    when :undercut then lowest ? lowest - @config.undercut_amount : current_price
    when :match    then average || current_price
    when :premium  then (average || current_price) * (1 + @config.premium_share)
    end
  end

  def effective_strategy
    return @config.strategy.to_sym unless @config.strategy == "by_stock"
    return :undercut if weeks_of_stock > 8
    return :premium if weeks_of_stock < 1
    :match
  end

  # The markup rule P* = C * e / (1 + e) only holds where demand is elastic (e < -1),
  # and only for a real estimate. Without one, the strategy price stands.
  def lean_towards_markup_rule(price, cost)
    e = @product.price_elasticity
    return price unless e && e < -1.0
    optimal = cost * e / (1 + e)
    price * (1 - ELASTICITY_WEIGHT) + optimal * ELASTICITY_WEIGHT
  end

  def stock_adjustment
    case weeks_of_stock
    when ...1 then 1.03
    when 1...4 then 1.0
    when 4...8 then 0.98
    else 0.95
    end
  end

  def weeks_of_stock
    @weeks_of_stock ||= begin
      weekly = SalesVelocity.weekly_average(@variant, weeks: 8)
      weekly.positive? ? @variant.total_on_hand.to_f / weekly : 99.0
    end
  end

  def floor(cost)
    [cost / (1 - @config.minimum_margin), @config.price_floor || 0].max
  end

  def ceiling
    @config.price_ceiling || current_price * 1.5
  end

  # A variant in an order that has reached payment keeps its price until the
  # order completes or is abandoned.
  def in_checkout?
    Spree::LineItem.joins(:order)
      .where(variant_id: @variant.id)
      .where(spree_orders: { state: %w[payment confirm], completed_at: nil })
      .where("spree_orders.updated_at > ?", 2.hours.ago)
      .exists?
  end

  def inputs(cost)
    {
      cost: cost.to_f,
      current_price: current_price.to_f,
      competitor_lowest: CompetitorPrice.lowest_total(@variant)&.to_f,
      competitor_average: CompetitorPrice.average_total(@variant)&.to_f,
      elasticity: @product.price_elasticity,
      weeks_of_stock: weeks_of_stock.round(2),
      strategy: effective_strategy
    }
  end
end

Writing prices into Solidus

Solidus stores prices as Spree::Price records per currency and, optionally, per country, and a configurable price selector picks the one that applies. The default selector chooses by currency and country.16 The engine therefore writes a normal price record, and the storefront, the cart and the feeds read it the usual way. You can swap the selector class through Spree::Config.variant_price_selector_class when you need prices per country or channel. I do not use that hook to price per customer, for the reasons above.

# app/services/price_writer.rb
class PriceWriter
  def apply!(variant, proposal, currency: "EUR")
    return if proposal.nil? || proposal.needs_review

    price = variant.prices.find_or_initialize_by(currency: currency, country_iso: nil)
    old_amount = price.amount
    return if old_amount && (proposal.amount - old_amount).abs < 0.01

    Spree::Price.transaction do
      price.update!(amount: proposal.amount)
      PriceChange.create!(
        variant: variant, currency: currency,
        old_amount: old_amount, new_amount: proposal.amount,
        reason: proposal.reason, inputs: proposal.inputs
      )
    end
  end
end

Proposals that hit the floor or the ceiling are not applied. They go to a short daily list for a person, because an engine pinned against a limit is usually telling you that a cost, a competitor match or an elasticity estimate is wrong.

The budget allocator

The allocator implements the score from the worked example. The first version filtered on a total_on_hand column and averaged price in SQL, but Solidus keeps stock in stock items and prices in their own table, so neither column exists on the variants table. This version computes both in Ruby.

# app/services/budget_allocator.rb
class BudgetAllocator
  def initialize(monthly_budget:, platform:)
    @monthly_budget = monthly_budget
    @platform = platform
  end

  def allocation
    scores = eligible_products.to_h { |product| [product, score(product)] }
    total = scores.values.sum
    return {} if total.zero?

    scores.transform_values { |s| (@monthly_budget * s / total).round(2) }
  end

  private

  def eligible_products
    Spree::Product.available.includes(:variants).select do |product|
      product.variants.any? { |v| v.cost_price.present? && v.total_on_hand.positive? }
    end
  end

  def score(product)
    margin(product) *
      (ConversionMetrics.rate_for(product, days: 30) || 0.0) *
      stock_factor(product) *
      competitive_factor(product)
  end

  def margin(product)
    options = Spree::Config.default_pricing_options
    rates = product.variants.filter_map do |v|
      price = v.price_for_options(options)&.amount
      next unless price&.positive? && v.cost_price
      (price - v.cost_price) / price
    end
    rates.empty? ? 0.0 : rates.sum / rates.size
  end

  def stock_factor(product)
    weekly = SalesVelocity.product_weekly_average(product, weeks: 8)
    weeks = weekly.positive? ? product.variants.sum(&:total_on_hand).to_f / weekly : 99.0
    case weeks
    when ...1 then 0.5
    when 1...2 then 0.8
    when 2...4 then 1.0
    when 4...8 then 1.3
    else 1.5
    end
  end

  def competitive_factor(product)
    options = Spree::Config.default_pricing_options
    positions = product.variants.filter_map do |v|
      lowest = CompetitorPrice.lowest_total(v)
      highest = CompetitorPrice.for_variant(v).map(&:total_price).max
      price = v.price_for_options(options)&.amount
      next unless lowest && price
      if price <= lowest then 1.2
      elsif price >= highest then 0.7
      else 1.0
      end
    end
    positions.empty? ? 1.0 : positions.sum / positions.size
  end
end

Sending budgets and prices to the platforms

In the Google Ads API a campaign budget is set in micros, a millionth of the account currency, and Google caps the effective monthly spend at 30.4 times the daily amount.17 So a monthly allocation becomes a daily budget by dividing by 30.4, not 30: the casserole's €1,884 becomes about €61.97 a day.

# app/services/google_ads_budgets.rb
class GoogleAdsBudgets
  def initialize(client: GoogleAdsClientFactory.build,
                 customer_id: Rails.application.credentials.google_ads[:customer_id])
    @client = client
    @customer_id = customer_id
  end

  def set_daily!(budget_resource_name:, monthly_amount:)
    daily = monthly_amount / 30.4
    operation = @client.operation.update_resource.campaign_budget(budget_resource_name) do |b|
      b.amount_micros = (daily * 1_000_000).round
    end
    @client.service.campaign_budget.mutate_campaign_budgets(
      customer_id: @customer_id, operations: [operation]
    )
  end
end

Meta sets budgets on the ad set through its Marketing API, with daily_budget in the account currency's smallest unit.18 Keep the Graph API version in configuration rather than in code: the first version hard coded v18.0, which is long out of date.

# app/services/meta_budgets.rb
class MetaBudgets
  def initialize
    creds = Rails.application.credentials.meta_ads
    @token = creds[:access_token]
    @base = "https://graph.facebook.com/#{creds[:graph_version]}"
  end

  def set_daily!(adset_id:, monthly_amount:)
    minor_units = (monthly_amount / 30.4 * 100).round
    response = Faraday.post("#{@base}/#{adset_id}", daily_budget: minor_units, access_token: @token)
    raise "Meta budget update failed: #{response.body}" unless response.success?
  end
end

Prices in the product feeds must follow the shop. Google crawls your landing pages and compares the price there with the price in your product data, and a mismatch can get products disapproved.19 Google sunset the Content API for Shopping on 18 August 2026 and requests now fail progressively, so feed updates go through the Merchant API.20 I keep that behind a small MerchantFeed wrapper, built from Google's migration guide, so the rest of the code does not care which API version is current.

The nightly job

# app/jobs/nightly_pricing_job.rb
class NightlyPricingJob < ApplicationJob
  queue_as :default

  def perform
    return unless PricingSwitch.on?   # one switch turns the whole loop off

    CompetitorPriceSyncJob.perform_now

    writer = PriceWriter.new
    Spree::Variant.joins(:product)
      .where(spree_products: { dynamic_pricing: true })
      .where.not(cost_price: nil)
      .find_each do |variant|
        writer.apply!(variant, PricingEngine.new(variant).propose)
      end

    MerchantFeed.push_changed_prices(since: 1.hour.ago)
    MetaCatalogue.push_changed_prices(since: 1.hour.ago)

    google = BudgetAllocator.new(monthly_budget: AdBudget.monthly(:google), platform: :google)
    google.allocation.each do |product, amount|
      mapping = CampaignMapping.find_by(product: product, platform: "google")
      next unless mapping
      GoogleAdsBudgets.new.set_daily!(budget_resource_name: mapping.budget_resource_name, monthly_amount: amount)
    end
  end
end
# config/recurring.yml (Solid Queue), or the equivalent in sidekiq-cron
production:
  nightly_pricing:
    class: NightlyPricingJob
    schedule: every day at 3am

Measuring whether it works

Measure the loop by profit, not by activity. Five numbers, weekly, against the weeks before the loop went live and, where you can, against a control group of products the loop does not touch.

Gross margin per order, which should rise if prices move towards the markup rule on elastic products. Gross profit per session, which combines price and conversion into the one number that matters. POAS per campaign, which should rise as budget moves towards profit. Price changes per product per week, where zero means the loop is not doing anything and many means it is chasing noise. And the review list: how many proposals hit a limit, and why.

The control group is the part people skip. Prices are rarely set at random, so a rise in margin after launch could be the season, a competitor going out of stock or a new product. Leaving a matched set of products on fixed prices for six to eight weeks is what tells you the loop earned the difference. The test design is in the elasticity article, and a simpler first step, with rules before models, is in dynamic pricing with AI.

What changes when marketing owns the levers

Marketing is usually handed a product, a price and a budget and asked to make the most of them. Price belongs to someone else, stock to operations and margin to finance. That is how a team can run excellent campaigns that sell, at a loss, a product nobody would have advertised if they had seen its margin.

The loop above puts price, stock, margin and ad spend into one place, with limits a person sets and a log a person reads. It is not autopilot. It is a set of decisions you would make anyway, made every night with the numbers in front of you, inside the law, and written down.

If you run a Solidus or Rails shop and want this built, I start with a free workshop and the first two weeks of work are on me. Bespoke Solidus code I write for your shop becomes yours on full payment. The elasticity estimates and pricing models are data science work: your raw data stays yours, and the terms for code and models are in the analytics and data science terms. Book the workshop and bring a year of orders.

If you run a Solidus or Rails shop and want pricing and ad budgets working from the same numbers, I run a free workshop and the first two weeks of work are on me. Bring a year of orders and your current ad accounts, and I will show you which products your budget should be backing.

Sources

  1. 1.

    Robert S. Pindyck, Lecture Notes on Pricing, 15.013 Industrial Economics for Strategic Decisions, MIT Sloan School of Management, August 2010, https://www.mit.edu/~rpindyck/Courses/Pricing_10.pdf

  2. 2.

    Directive (EU) 2019/2161 of the European Parliament and of the Council (the Omnibus Directive), recital 45 and Article 2 (inserting Article 6a into Directive 98/6/EC), EUR-Lex, 2019, https://eur-lex.europa.eu/legal-content/EN/TXT/HTML/?uri=CELEX:32019L2161

  3. 3.

    Law Reform Commission, Consumer Protection Act 2007, revised, section 43 (Misleading: false, misleading or deceptive information), Revised Acts, https://revisedacts.lawreform.ie/eli/2007/act/19/revised/en/html

  4. 4.

    Law Reform Commission, Consumer Protection Act 2007, revised, section 55 (Prohibited commercial practices), subsection (1)(n), Revised Acts, https://revisedacts.lawreform.ie/eli/2007/act/19/revised/en/html

  5. 5.

    European Union (Requirements to Indicate Product Prices) (Amendment) Regulations 2022, S.I. No. 597 of 2022, regulation 4 (inserting Regulation 5A into S.I. No. 639 of 2002), Irish Statute Book, https://www.irishstatutebook.ie/eli/2022/si/597/made/en/html

  6. 6.

    Competition and Consumer Protection Commission, Price reductions, CCPC, accessed November 2026, https://www.ccpc.ie/information-for-businesses/selling-goods-and-services/pricing-and-price-reductions/price-reductions

  7. 7.

    Court of Justice of the European Union, judgment of 26 September 2024, Verbraucherzentrale Baden-Württemberg v Aldi Süd, case C-330/23, https://curia.europa.eu/juris/liste.jsf?num=C-330/23&language=en

  8. 8.

    Government of Ireland, Consumer Rights Act 2022, Schedule 3 (Information to be provided: off premises contract or distance contract), clause (i), Irish Statute Book, 2022, https://www.irishstatutebook.ie/eli/2022/act/37/schedule/3/enacted/en/html

  9. 9.

    Regulation (EU) 2016/679 (General Data Protection Regulation), Article 22(1) to (3), automated individual decision making, including profiling, EUR-Lex, https://eur-lex.europa.eu/legal-content/EN/TXT/HTML/?uri=CELEX:32016R0679

  10. 10.

    Equal Status Act 2000, section 5 (Disposal of goods and provision of services), with the discriminatory grounds in section 3, Irish Statute Book, https://www.irishstatutebook.ie/eli/2000/act/8/section/5/enacted/en/html

  11. 11.

    European Communities (Electronic Communications Networks and Services) (Privacy and Electronic Communications) Regulations 2011, S.I. No. 336 of 2011, regulation 5, Irish Statute Book, https://www.irishstatutebook.ie/eli/2011/si/336/made/en/print

  12. 12.

    Competition Act 2002, section 4, Irish Statute Book, https://www.irishstatutebook.ie/eli/2002/act/14/section/4/enacted/en/html, and Treaty on the Functioning of the European Union, Article 101, EUR-Lex, https://eur-lex.europa.eu/legal-content/EN/TXT/HTML/?uri=CELEX:12016E101

  13. 13.

    European Commission, Guidelines on the applicability of Article 101 of the Treaty on the Functioning of the European Union to horizontal co operation agreements, Official Journal of the European Union, C 259, 21 July 2023, paragraphs 379 and 402, https://eur-lex.europa.eu/legal-content/EN/TXT/HTML/?uri=CELEX:52023XC0721%2801%29

  14. 14.

    Competition and Consumer Protection Commission, Understanding and preventing price fixing, CCPC, accessed November 2026, https://www.ccpc.ie/information-for-businesses/guidance-for-businesses/competition-law-guidance/competition-law-breaches/cartels/price-fixing

  15. 15.

    Emilio Calvano, Giacomo Calzolari, Vincenzo Denicolò and Sergio Pastorello, Artificial Intelligence, Algorithmic Pricing, and Collusion, American Economic Review, volume 110, issue 10, pages 3267 to 3297, 2020, https://www.aeaweb.org/articles?id=10.1257/aer.20190623

  16. 16.

    Solidus contributors, Spree::Variant::PriceSelector, Solidus source code on GitHub, https://github.com/solidusio/solidus/blob/main/core/app/models/spree/variant/price_selector.rb

  17. 17.

    Google, CampaignBudget (field amount_micros), Google Ads API reference, accessed November 2026, https://developers.google.com/google-ads/api/reference/rpc/latest/CampaignBudget

  18. 18.

    Meta, Ad Set reference (field daily_budget), Marketing API documentation, accessed November 2026, https://developers.facebook.com/docs/marketing-api/reference/ad-campaign/

  19. 19.

    Google, How to fix: Mismatched product price, Google Merchant Center Help, accessed November 2026, https://support.google.com/merchants/answer/6098334

  20. 20.

    Google, Content API for Shopping (deprecated), notice of the sunset on 18 August 2026 and the Merchant API migration guide, Google for Developers, accessed November 2026, https://developers.google.com/shopping-content/guides/quickstart

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.