Build AI Trading Agents with Bitquery Solana Data
In this section, we will explore how to use Bitquery APIs and real-time streams to build AI-enabled trading agents for the Solana blockchain.
Your AI Trading Agent's Mission:
You are a specialized trading agent operating on the Solana blockchain, you will optimize an existing portfolio by analyzing and trading trending tokens using Bitquery data. Your primary goal is to identify profitable tokens in the market, assess wallet balances, and execute calculated swap decisions to enhance portfolio value.
Trading Decision Process
This is a rough draft of what an AI agent can do using on-chain and off-chain data:
- Use trending data to identify promising tokens with potential profit.
- For each trending token, retrieve detailed information to evaluate its market cap, liquidity, volatility, and security.
- Check the wallet balance to understand the available assets and decide on a safe percentage to invest.
- Execute swaps to acquire trending tokens, ensuring the chosen amount.
- Continuously monitor token performance and adjust holdings to maximize profits. For this you can use Bitquery Shred Streams to monitor token prices, new token creation and other activities with sub-second latency.
Code Structure and Logic: A Good Starting Point
Your code sets up a flexible AI trading agent framework, handling:
- backtesting : historical simulation.
- live mode: real-time trading/decision making
- Portfolio tracking (cash, positions, realized gains)
- Integration with an AI model (likely LLM) to guide trading decisions
- where the AI agent makes data-driven trading decisions based on Bitquery Solana data.
Key Bitquery Streams and Queries for Trading Agents
1. Top Trending Tokens
Detect tokens with rising popularity and trader activity.
Docs: Top 10 Trending Solana Tokens
Click to expand GraphQL query
query TrendingTokens {
Solana(network: solana, dataset: realtime) {
DEXTradeByTokens(
limit: {count: 10}
orderBy: {descendingByField: "tradesCountWithUniqueTraders"}
where: {Trade: {Currency: {MintAddress: {notIn: ["So11111111111111111111111111111111111111112","11111111111111111111111111111111"]}}}}
) {
Trade {
Currency {
Name
Symbol
MintAddress
}
}
tradesCountWithUniqueTraders: count(distinct: Transaction_Signer)
}
}
}
Use: Filter tokens with rising trader activity to shortlist tokens to buy.
2. Volatility of a Token
Measure short-term price fluctuations to assess risk and profit potential.
Query Link: Volatility of a Pair on Solana
Click to expand GraphQL query
query Volatility {
Solana(dataset: realtime, network: solana) {
DEXTrades(
where: {
Trade: {
Buy: {
Currency: {
MintAddress: {
is: "6p6xgHyF7AeE6TZkSmFsko444wqoP15icUSqi2jfGiPN"
}
}
}
Sell: {
Currency: {
MintAddress: {
is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
}
}
}
}
}
) {
volatility: standard_deviation(of: Trade_Buy_Price)
}
}
}
Use: High volatility can indicate short-term profit opportunities but also increased risk.
3. Marketcap & Liquidity Pool Analysis
Evaluate token liquidity to avoid low-volume or illiquid tokens.
Docs: Top Pools based on Liquidity
Click to expand GraphQL query
query GetTopPoolsByDex {
Solana {
DEXPools(
orderBy: { descending: Pool_Quote_PostAmount }
where: {
Block: { Time: { after: "2024-08-27T12:00:00Z" } }
Transaction: { Result: { Success: true } }
}
limit: { count: 10 }
) {
Pool {
Market {
MarketAddress
BaseCurrency {
MintAddress
Symbol
Name
}
QuoteCurrency {
MintAddress
Symbol
Name
}
}
Dex {
ProtocolName
ProtocolFamily
}
Quote {
PostAmount
PostAmountInUSD
PriceInUSD
}
Base {
PostAmount
}
}
}
}
}
Marketcap of a token
You can fetch Marketcap of a token using below query.
Click to expand GraphQL query
query MyQuery {
Solana {
TokenSupplyUpdates(
where: {TokenSupplyUpdate: {Currency: {MintAddress: {is: "6D7NaB2xsLd7cauWu1wKk6KBsJohJmP2qZH9GEfVi5Ui"}}}}
limit: {count: 1}
orderBy: {descending: Block_Time}
) {
TokenSupplyUpdate {
PostBalanceInUSD
}
}
}
}
Use: Focus on tokens with strong liquidity to ensure reliable entry and exit points.
4. Wallet Balances Monitoring
Review current portfolio composition before making swaps.
Docs: Account Balances on Solana
Click to expand GraphQL query
query MyQuery {
Solana {
BalanceUpdates(
where: { BalanceUpdate: { Account: { Owner: { is: "WALLET ADDRESS" } } } }
orderBy: { descendingByField: "BalanceUpdate_Balance_maximum" }
) {
BalanceUpdate {
Balance: PostBalance(maximum: Block_Slot)
Currency {
Name
Symbol
}
}
}
}
}
Use: Determine available assets and calculate safe investment amounts for token swaps.
5. DEX Trade Streams for Real-Time Trades
Subscribe to continuous streams of Solana DEX trades for live market intelligence.
The same stream can be obtained with lower latency via Kafka containing Solana Shreds.
Click to expand GraphQL Stream
subscription {
Solana {
DEXTrades {
Block {
Time
Slot
}
Transaction {
Signature
Index
Result {
Success
}
}
Trade {
Index
Dex {
ProgramAddress
ProtocolFamily
ProtocolName
}
Buy {
Amount
Account {
Address
}
Currency {
MetadataAddress
Key
MintAddress
IsMutable
EditionNonce
Decimals
CollectionAddress
Fungible
Symbol
Native
Name
}
Price
PriceInUSD
Order {
LimitPrice
LimitAmount
OrderId
}
}
Market {
MarketAddress
}
Sell {
Account {
Address
}
Currency {
IsMutable
Decimals
CollectionAddress
Fungible
Symbol
Native
Name
}
Price
PriceInUSD
}
}
}
}
}
Use: React instantly to time-sensitive trades.
6. Token Holders Distribution (Security Check)
Check token decentralization to avoid risky, whale-dominated assets.
Click to expand GraphQL query
query MyQuery {
Solana {
BalanceUpdates(
orderBy: { descendingByField: "BalanceUpdate_Holding_maximum" }
where: {
BalanceUpdate: {
Currency: {
MintAddress: { is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" }
}
}
Transaction: { Result: { Success: true } }
}
) {
BalanceUpdate {
Currency {
Name
MintAddress
Symbol
}
Account {
Address
}
Holding: PostBalance(maximum: Block_Slot, selectWhere: { gt: "0" })
}
}
}
}
Use: Avoid tokens with highly concentrated ownership that may be vulnerable to manipulation.
7. Avoiding Bots with DEXRabbit (Built by Bitquery)
Your AI Trading Agent should monitor bot activity on DEXs. Bots can cause sudden price spikes, wash trading, or manipulate token prices, posing risks to human traders.
DexRabbit.com, built on Bitquery data, offers charts and dashboards to detect bot activity in real-time.
Key Bot Activity Indicators to Monitor:
Indicator | Description |
---|---|
Highly repetitive trade patterns | Identical trades happening in short intervals suggest bot activity. |
Large trade bursts at odd hours | Bots often execute trades at low-liquidity times to influence price. |
Frequent pump-and-dump patterns | Sharp price surges followed by rapid sell-offs indicate manipulation. |
Unusual token holder concentration | Bots may use multiple wallets to appear as unique traders. |
Calculating Trading Indicators
You can SMA, EMA, RSI etc with Bitquery data. A tutorial is available here
Your AI Agent can reconstruct price charts and calculate:
SMA 50: Simple Moving Average over last 50 data points (could be trades, time intervals, etc.).
SMA 200: Simple Moving Average over last 200 data points.
Detect crossovers:
SMA 50 crosses above SMA 200 → Consider Buy.
SMA 50 crosses below SMA 200 → Consider Sell.
This logic can be integrated into the AI Trading Loop along with the on-chain analysis.
Building the AI Trading Loop
Your AI Trading Agent combines the above streams as follows:
Fetch Top Trending Tokens to shortlist candidates.
For each token:
- Analyze Liquidity, Volatility, and Holders Distribution.
Check Wallet Balances to calculate possible investment amount.
Use Real-Time Trade Streams to time the market entry.
Execute Swaps on high-potential tokens.
Continuously monitor market data and adjust holdings as needed.
Next Steps
- Integrate these Bitquery APIs into your AI agent.
- Define risk management parameters, such as maximum percentage of balance per trade.
- Automate decision-making logic based on market data.
- Continuously refine and improve trading strategies using real-time data.
You can also integrate off-chain information like Twitter feeds to decide if a token is worth investing
- Combine with NLP (Natural Language Processing) to do sentiment analysis on tweets.
- Build alert systems based on specific keywords or sentiment spikes.
- Monitor tweets from key influencers and trigger trades based on their content.
- Use Twitter data as a factor in your AI models' decision-making.
This material is for educational and informational purposes only and is not intended as investment advice. The content reflects the author's personal research and understanding. While specific investments and strategies are mentioned, no endorsement or association with these entities is implied. Readers should conduct their own research and consult with qualified professionals before making any investment decisions. Bitquery is not liable for any losses or damages resulting from the application of this information.