Skip to content

API Code Examples

Practical examples for integrating with GoonPad API.

JavaScript / Node.js

Fetch All Tokens

javascript
async function getAllTokens() {
  const response = await fetch('https://api.goonpad.dev/api/tokens')
  const result = await response.json()

  if (!result.success) {
    console.error('Error:', result.error)
    return []
  }

  const { data, source } = result
  console.log(`Found ${data.length} tokens (source: ${source})`)

  data.forEach(token => {
    console.log(`${token.symbol}: ${token.marketCap} SOL market cap`)
  })

  return data
}

getAllTokens()

Monitor Token Price

javascript
import { io } from 'socket.io-client'

async function monitorToken(address) {
  const socket = io('https://api.goonpad.dev')

  socket.on('connect', () => {
    console.log('Connected to GoonPad')
    socket.emit('subscribe', `token:${address}`)
  })

  socket.on(`token:${address}:update`, (data) => {
    console.log('Token update:', data)
    if (data.data) {
      console.log(`Last Buy: ${data.data.lastBuy} SOL`)
      console.log(`Last Sell: ${data.data.lastSell} SOL`)
    }
  })

  // Also subscribe to general token updates
  socket.emit('subscribe', 'tokens')
  socket.on('tokens:update', (data) => {
    const tokenUpdate = data.data.find(t => t.tokenAddress === address)
    if (tokenUpdate) {
      console.log(`Price: ${tokenUpdate.price} SOL`)
      console.log(`Market Cap: ${tokenUpdate.marketCap} SOL`)
      console.log(`Progress: ${(tokenUpdate.bondingCurveProgress * 100).toFixed(1)}%`)
    }
  })
}

monitorToken('YOUR_TOKEN_ADDRESS')

Track Graduations

javascript
import { io } from 'socket.io-client'

const socket = io('https://api.goonpad.dev')

socket.on('connect', () => {
  console.log('Connected to GoonPad')
  socket.emit('subscribe', 'feed:live')
})

socket.on('feed:live:update', (event) => {
  if (event.action === 'graduated') {
    console.log('🎉 Token Graduated!')
    console.log(`Token: ${event.token}`)
    console.log(`Address: ${event.tokenAddress}`)
    console.log(`User: ${event.userFull}`)

    // Send notification, update database, etc.
  }
})

Python

Fetch Tokens (HTTP)

python
import requests

def get_all_tokens():
    response = requests.get('https://api.goonpad.dev/api/tokens')
    result = response.json()

    if not result.get('success'):
        print(f"Error: {result.get('error')}")
        return []

    data = result['data']
    source = result.get('source', 'unknown')

    print(f"Found {len(data)} tokens (source: {source})")

    for token in data:
        print(f"{token['symbol']}: {token['marketCap']} SOL market cap")

    return data

tokens = get_all_tokens()

WebSocket Monitor

python
import socketio
import time

# Create Socket.io client
sio = socketio.Client()

@sio.on('connect')
def on_connect():
    print('✅ Connected to GoonPad')
    sio.emit('subscribe', 'tokens')
    sio.emit('subscribe', 'feed:live')

@sio.on('tokens:update')
def on_tokens_update(data):
    print(f"📊 Received {len(data['data'])} token updates")
    for token in data['data'][:3]:  # Show first 3
        print(f"  {token['tokenAddress'][:8]}... MC: {token['marketCap']} SOL")

@sio.on('feed:live:update')
def on_live_update(event):
    action = event['action']
    if action == 'bought':
        print(f"🟢 {event['user']} bought {event['amount']} SOL of {event['token']}")
    elif action == 'sold':
        print(f"🔴 {event['user']} sold {event['amount']} SOL of {event['token']}")
    elif action == 'graduated':
        print(f"🎉 {event['token']} graduated!")

@sio.on('disconnect')
def on_disconnect():
    print('❌ Disconnected from GoonPad')

# Connect and keep alive
sio.connect('https://api.goonpad.dev')
sio.wait()

Install required package:

bash
pip install python-socketio[client]

Discord Bot Example

javascript
const { Client, EmbedBuilder } = require('discord.js')
const { io } = require('socket.io-client')

const bot = new Client({ intents: ['Guilds', 'GuildMessages'] })
const socket = io('https://api.goonpad.dev')

// Subscribe to live feed for graduations
socket.on('connect', () => {
  console.log('✅ Connected to GoonPad WebSocket')
  socket.emit('subscribe', 'feed:live')
})

// Send Discord notification on graduation
socket.on('feed:live:update', (event) => {
  if (event.action === 'graduated') {
    const embed = new EmbedBuilder()
      .setTitle('🎉 Token Graduated!')
      .setDescription(`**${event.token}** just graduated!`)
      .addFields(
        { name: 'Token', value: event.token, inline: true },
        { name: 'Address', value: event.tokenAddress.slice(0, 16) + '...', inline: true }
      )
      .setColor('#FF9000')
      .setTimestamp()
      .setFooter({ text: 'GoonPad Platform' })

    const channel = bot.channels.cache.get('YOUR_CHANNEL_ID')
    if (channel) {
      channel.send({ embeds: [embed] })
    }
  }
})

bot.on('ready', () => {
  console.log(`Logged in as ${bot.user.tag}`)
})

bot.login('YOUR_BOT_TOKEN')

Install dependencies:

bash
npm install discord.js socket.io-client

Trading Bot Skeleton

javascript
import { io } from 'socket.io-client'

class GoonPadTradingBot {
  constructor(strategy) {
    this.strategy = strategy
    this.socket = io('https://api.goonpad.dev')
    this.positions = new Map()
    this.tokenData = new Map()
  }

  start() {
    this.socket.on('connect', () => {
      console.log('✅ Bot connected to GoonPad')
      this.socket.emit('subscribe', 'tokens')
      this.socket.emit('subscribe', 'feed:live')
    })

    this.socket.on('tokens:update', (data) => {
      if (data.success && data.data) {
        data.data.forEach(token => {
          this.tokenData.set(token.tokenAddress, token)
          this.handleTokenUpdate(token)
        })
      }
    })

    this.socket.on('feed:live:update', (event) => {
      this.handleLiveEvent(event)
    })

    this.socket.on('disconnect', () => {
      console.log('❌ Bot disconnected, will auto-reconnect')
    })
  }

  async handleTokenUpdate(token) {
    const signal = this.strategy.analyze(token)

    if (signal === 'BUY' && !this.positions.has(token.tokenAddress)) {
      await this.executeBuy(token.tokenAddress, 0.1) // 0.1 SOL
    } else if (signal === 'SELL' && this.positions.has(token.tokenAddress)) {
      await this.executeSell(token.tokenAddress)
    }
  }

  handleLiveEvent(event) {
    // React to live events like graduations
    if (event.action === 'graduated') {
      console.log(`🎉 ${event.token} graduated - selling position`)
      if (this.positions.has(event.tokenAddress)) {
        this.executeSell(event.tokenAddress)
      }
    }
  }

  async executeBuy(tokenAddress, solAmount) {
    console.log(`🟢 Buying ${solAmount} SOL of ${tokenAddress}`)
    // Implement actual buy logic with Solana wallet
    // Example: Use @solana/web3.js to execute trade
    this.positions.set(tokenAddress, {
      amount: solAmount,
      timestamp: Date.now()
    })
  }

  async executeSell(tokenAddress) {
    console.log(`🔴 Selling ${tokenAddress}`)
    // Implement actual sell logic
    this.positions.delete(tokenAddress)
  }

  stop() {
    this.socket.disconnect()
  }
}

// Bonding curve progress momentum strategy
const strategy = {
  analyze: (token) => {
    const progress = token.bondingCurveProgress || 0
    const marketCap = token.marketCap || 0

    // Buy if token is gaining momentum (40-70% progress)
    if (progress > 0.4 && progress < 0.7 && marketCap < 70) {
      return 'BUY'
    }

    // Sell if token is close to graduation (avoid risk)
    if (progress > 0.85 || marketCap > 80) {
      return 'SELL'
    }

    return 'HOLD'
  }
}

const bot = new GoonPadTradingBot(strategy)
bot.start()

// Graceful shutdown
process.on('SIGINT', () => {
  console.log('\nShutting down bot...')
  bot.stop()
  process.exit(0)
})

Portfolio Tracker

javascript
async function getPortfolio(walletAddress) {
  // Get all tokens
  const response = await fetch('https://api.goonpad.dev/api/tokens')
  const { data: tokens } = await response.json()

  // Calculate portfolio value
  let totalValue = 0
  const holdings = []

  for (const token of tokens) {
    // Check if wallet holds this token
    // (You'd use Solana RPC for this)
    const balance = await getTokenBalance(walletAddress, token.address)

    if (balance > 0) {
      const value = balance * token.pricePerToken
      totalValue += value

      holdings.push({
        symbol: token.symbol,
        balance: balance,
        value: value,
        price: token.pricePerToken
      })
    }
  }

  return {
    totalValue,
    holdings
  }
}

Telegram Bot

javascript
const { Telegraf } = require('telegraf')
const fetch = require('node-fetch')

const bot = new Telegraf('YOUR_BOT_TOKEN')

// /price command
bot.command('price', async (ctx) => {
  const symbol = ctx.message.text.split(' ')[1]

  const response = await fetch('https://api.goonpad.dev/api/tokens')
  const { data: tokens } = await response.json()

  const token = tokens.find(t => t.symbol === symbol.toUpperCase())

  if (token) {
    ctx.reply(
      `💰 ${token.name} (${token.symbol})\n` +
      `Price: ${token.pricePerToken} SOL\n` +
      `Market Cap: ${token.marketCap} SOL\n` +
      `24h Volume: ${token.volume24h} SOL\n` +
      `Holders: ${token.holders}`
    )
  } else {
    ctx.reply(`Token ${symbol} not found`)
  }
})

// /trending command
bot.command('trending', async (ctx) => {
  const response = await fetch('https://api.goonpad.dev/api/tokens/trending')
  const { data: tokens } = await response.json()

  let message = '📈 Trending Tokens:\n\n'

  tokens.slice(0, 5).forEach((token, i) => {
    message += `${i + 1}. ${token.symbol} - ${token.marketCap} SOL\n`
  })

  ctx.reply(message)
})

bot.launch()

Next Steps


Build something awesome! Share what you create with the community.

Built with passion on Solana