Carbon DeFi Dev
  • Carbon DeFi
    • Introducing Carbon DeFi
      • What Makes Carbon DeFi Unique?
      • Fees & Payments
      • Resources
    • Security & Audits
  • Contracts & Functions
    • Contracts
      • CarbonController
      • CarbonVortex
      • CarbonVortexBridge
      • Deployments
        • Mainnet Contracts
        • Testnet Contracts
    • CarbonController Functions
      • Write Functions
        • Transaction Prerequisites
          • approve() / allowance()
        • Trade
          • tradeBySourceAmount()
          • tradeByTargetAmount()
        • Strategy Management
          • createStrategy()
          • updateStrategy
          • deleteStrategy()
      • Read Functions
        • controllerType()
        • tradingFeePPM()
        • pairTradingFeePPM()
        • pair()
        • pairs()
        • strategy()
        • strategiesByPair()
        • strategiesByPairCount()
        • calculateTradeSourceAmount()
        • calculateTradeTargetAmount()
      • Data & Events
        • TradingFeePPMUpdated()
        • PairCreated()
        • StrategyCreated()
        • StrategyDeleted()
        • StrategyUpdated()
        • TokensTraded()
        • FeesWithdrawn()
    • CarbonVortex Functions
      • Write Functions
        • trade()
        • execute()
      • Read Functions
        • amountAvailableForTrading()
        • availableTokens()
        • expectedTradeInput()
        • expectedTradeReturn()
        • finalTargetToken()
        • minTargetTokenSaleAmount()
        • minTokenSaleAmount()
        • pairDisabled()
        • priceDecayHalfLife()
        • rewardsPPM()
        • targetToken()
        • targetTokenPriceDecayHalfLife()
        • targetTokenSaleAmount()
        • tokenPrice()
        • totalCollected()
        • tradingEnabled()
    • CarbonVortexBridge Functions
      • Write Functions
        • Bridge()
  • Rest API
    • Carbon DeFi Public REST API
  • Developer Guides
    • Carbon DeFi SDK
      • Getting started
      • Interacting with the SDK
        • Managing Strategies
        • Performing Trades
        • Getting User and Pair Data
        • Collecting Liquidity Data
      • SDK Functions
        • constructor
        • startDataSync
        • getCachedPairs
        • hasLiquidityByPair
        • getLiquidityByPair
        • getUserStrategies
        • getTradeData
        • composeTradeByTargetTransaction
        • composeTradeBySourceTransaction
        • createBuySellStrategy
        • updateStrategy
        • deleteStrategy
        • getMinRateByPair
        • getMaxRateByPair
        • getRateLiquidityDepthByPair
    • The Carbon DeFi versus Uniswap V3 Invariant Functions
    • Carbon DeFi Subgraph
      • Accessing the Subgraph
      • Creating Subgraph Queries
      • Subgraph Query in Python
      • Sample Subgraph Queries
    • Using CarbonVortex
      • CarbonVortex Dynamics
Powered by GitBook
On this page
  1. Developer Guides
  2. Carbon DeFi Subgraph

Subgraph Query in Python

PreviousCreating Subgraph QueriesNextSample Subgraph Queries

Last updated 5 months ago

The following example queries the Carbon DeFi Subgraph using Python.

1. Copy the following code snippet into a Python development environment:

Note that you must assign the value for "GRAPH_API_KEY" with your API key. This example acquires the key from an .env file. To get an API key, visit:

import requests
import os

GRAPH_API_KEY = os.environ.get("GRT_API_KEY")

# function to use requests.post to make an API call to the subgraph url
def run_query(q):

    # endpoint where you are making the request
    request = requests.post(f'https://gateway-arbitrum.network.thegraph.com/api/{GRAPH_API_KEY}/subgraphs/id/3oYNFcwAGk5mVtzzMTDjanoMRsZRCGk88EFRn75dLRyp'
                            '',
                            json={'query': query})
    if request.status_code == 200:
        return request.json()
    else:
        raise Exception('Query failed. return code is {}.      {}'.format(request.status_code, query))


# The Graph query
query = """

{
  pairs {
    token0 {
      symbol
    }
    token1 {
      symbol
    }
  }
}
"""

result = run_query(query)

pairs = result['data']['pairs']

print(f"number of pairs from subgraph: {len(pairs)}")
print(f"first pair: {pairs[0]}")

2. Run the code!

If successful, you will see a printout of:

  • The number of pairs found in Carbon DeFi

  • The token symbols of the first pair

The printout should look like:

number of pairs from subgraph: 87

first pair: {'token0': {'symbol': 'BIAO'}, 'token1': {'symbol': 'ETH'}}

https://thegraph.com/studio/apikeys/