get_last_transaction()

Retrieve the most recent transaction for real-time price discovery and market monitoring

Price Discovery
Latest price
Activity Monitor
Track trades
Liquidity
Pool changes
Real-Time
Latest data

Overview

The get_last_transaction() method retrieves the most recent transaction for a specific trading pair on the Solana blockchain. This is essential for real-time price discovery, market activity monitoring, and building responsive trading applications.

Price Discovery

Get the latest transaction price

Market Monitoring

Track trading activity patterns

Liquidity Changes

Monitor liquidity pool updates

Activity Alerts

Detect new transactions for notifications

Method Signature

python
def get_last_transaction(self, pair_address: str) -> Dict

Parameters

pair_address (str, required)

  • Description: The Solana trading pair address to query
  • Format: Base58-encoded Solana public key
  • Example: "Cr8Qy7quTPDdR3sET6fZk7bRFtiDFLeuwntgZGKJrnAY"

Return Value

Returns a dictionary containing the last transaction details:

python
{
    "signature": str,           # Transaction signature (unique ID)
    "pairAddress": str,         # Trading pair address
    "type": str,                # "buy" or "sell"
    "createdAt": int,           # Unix timestamp (milliseconds)
    "liquiditySol": float,      # SOL liquidity after transaction
    "liquidityToken": float,    # Token liquidity after transaction
    "makerAddress": str,        # Wallet that initiated transaction
    "priceSol": float,          # Price in SOL per token
    "priceUsd": float,          # Price in USD per token
    "tokenAmount": float,       # Amount of tokens traded
    "totalSol": float,          # Total SOL in transaction
    "totalUsd": float,          # Total USD value
    "innerIndex": int,          # Inner instruction index
    "outerIndex": int           # Outer instruction index
}

Price Data

priceUsd, priceSol - Current transaction prices

Transaction Type

type - "buy" or "sell" indicator

Liquidity

liquiditySol, liquidityToken - Pool state

Timing

createdAt - Millisecond precision timestamp

Basic Usage Examples

Example 1: Get Last Transaction

Retrieve the most recent transaction for a pair.

python
from axiomtradeapi import AxiomTradeClient

client = AxiomTradeClient()
client.login("username", "password")

pair_address = "Cr8Qy7quTPDdR3sET6fZk7bRFtiDFLeuwntgZGKJrnAY"
last_tx = client.get_last_transaction(pair_address)

print(f"Last transaction: {last_tx['type']}")
print(f"Price: ${last_tx['priceUsd']:.8f}")
print(f"Amount: {last_tx['tokenAmount']:,.0f} tokens")
print(f"Total Value: ${last_tx['totalUsd']:.2f}")

Example 2: Check Transaction Time

Calculate time since last trade.

python
from datetime import datetime

last_tx = client.get_last_transaction(pair_address)

# Convert timestamp to readable format
timestamp = last_tx['createdAt'] / 1000
tx_time = datetime.fromtimestamp(timestamp)

print(f"Last trade: {tx_time.strftime('%Y-%m-%d %H:%M:%S')}")

# Calculate time since last trade
time_ago = datetime.now() - tx_time
minutes_ago = time_ago.total_seconds() / 60

print(f"Time since last trade: {minutes_ago:.1f} minutes ago")

Example 3: Monitor Buy vs Sell Pressure

Check market sentiment from last transaction.

python
last_tx = client.get_last_transaction(pair_address)

tx_type = last_tx['type']
if tx_type == "buy":
    print("✅ Last transaction was a BUY")
    print(f"   Amount: ${last_tx['totalUsd']:.2f}")
elif tx_type == "sell":
    print("❌ Last transaction was a SELL")
    print(f"   Amount: ${last_tx['totalUsd']:.2f}")

print(f"Current liquidity: {last_tx['liquiditySol']:.2f} SOL")

Advanced Examples

Advanced usage patterns for production applications:

Real-Time Price Monitor

Track price changes continuously

Activity Detector

Alert on trading activity patterns

Liquidity Tracker

Monitor pool liquidity changes

Frequency Analyzer

Analyze transaction velocity

Full advanced examples with complete code are available in the GitHub repository

View Examples on GitHub

Best Practices

1. Cache Transaction Data

python
# Don't poll too frequently
last_check = None
cache_duration = 10  # seconds

def get_cached_transaction(client, pair_address):
    global last_check, cached_data
    
    now = time.time()
    if last_check and (now - last_check) < cache_duration:
        return cached_data
    
    cached_data = client.get_last_transaction(pair_address)
    last_check = now
    return cached_data

2. Monitor Data Freshness

python
from datetime import datetime, timedelta

def is_data_fresh(last_tx, max_age_minutes=5):
    """Check if transaction data is recent"""
    tx_time = datetime.fromtimestamp(last_tx['createdAt'] / 1000)
    age = datetime.now() - tx_time
    return age < timedelta(minutes=max_age_minutes)

# Usage
last_tx = client.get_last_transaction(pair_address)
if not is_data_fresh(last_tx):
    print("⚠️  Warning: Data may be stale")

3. Use Appropriate Polling Intervals

python
# For high-frequency monitoring
high_frequency = 5  # seconds (active trading)

# For price displays
medium_frequency = 15  # seconds (dashboards)

# For background monitoring
low_frequency = 60  # seconds (alerts)

# Choose based on your use case
time.sleep(medium_frequency)

Important Notes

⚠️ Data Freshness

Transaction data reflects the last trade, which may be minutes or hours old for low-activity pairs

⚠️ Rate Limiting

Don't poll too frequently; implement caching and reasonable intervals

⚠️ Error Handling

Implement robust retry logic for network issues and invalid pair addresses

Troubleshooting

Issue: Stale Data (Old Transaction)

Solution: Check transaction timestamp

python
last_tx = client.get_last_transaction(pair_address)
tx_age_seconds = (time.time() * 1000 - last_tx['createdAt']) / 1000

if tx_age_seconds > 300:  # 5 minutes
    print(f"⚠️  Data is {tx_age_seconds/60:.1f} minutes old")
    print("Pair may have low trading activity")

Issue: Rate Limiting (429 Errors)

Solution: Implement exponential backoff

python
import time
from requests.exceptions import HTTPError

def get_tx_with_backoff(client, pair_address):
    backoff = 1
    max_backoff = 32
    
    while True:
        try:
            return client.get_last_transaction(pair_address)
        except HTTPError as e:
            if e.response.status_code == 429:
                time.sleep(backoff)
                backoff = min(backoff * 2, max_backoff)
            else:
                raise

Need Help?

Our support team can help you with transaction monitoring and real-time data

Related Documentation

Build Real-Time Trading Systems

Need help implementing real-time price feeds and activity monitoring? We're here to help.

Open Source

Contribute to AxiomTradeAPI

View on GitHub

Community

Join 1000+ developers

Join Discord

Custom Development

Professional bot building

Get Started