paint-brush
Your First Simple Crypto Trading Bot Using LunarCrush and 3Commasby@lunarcrush
3,727 reads
3,727 reads

Your First Simple Crypto Trading Bot Using LunarCrush and 3Commas

by LunarCrushSeptember 13th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

The LunarCrush API is perfect for traders who want to write scripts and work with bots to trigger specific trade activity. Lunarcrush monitors social for signals that will identify your next asset opportunity. 3Commas has an API that can be used in conjunction with Lunar Crush API. 3Commas is a way to take botted action when the LunarCrush research reaches specific thresholds that you determine and design in your own scripted bot. This article details the code how to do this.
featured image - Your First Simple Crypto Trading Bot Using LunarCrush and 3Commas
LunarCrush HackerNoon profile picture


As a trader, you might wonder how you can take your trading to the next level. The LunarCrush API is perfect for traders who want to write scripts and work with bots to trigger specific trade activity, but you need a platform that will let you perform the trades. LunarCrush monitors the internet for signals that will identify your next asset opportunity.


If you’re familiar with 3Commas, then you know that it’s a platform for trading with bots. You connect your favorite exchange to your 3Commas dashboard account, and you can automate much of the research and trading that takes hours to do manually. The platform also has an API that can be used in conjunction with the LunarCrush API. LunarCrush serves as your automated research tool, and the 3Commas API serves as a way to take botted action when the LunarCrush research reaches specific thresholds that you determine and design in your scripted bot.

The LunarCrush API returns numerous signals that can be used in custom trader scripts. Using custom scripts with LunarCrush and 3Commas gives you more flexibility in what you want to do instead of being tied to preset features coded in the dashboard. This simple starter guide will help new traders get acclimated to the LunarCrush API and see what it can do for trader bots.

In this example, we’ll use Galaxy Score, which is a score calculated from several social and price metrics. You can read about the other data LunarCrush makes available from the API, but this guide will focus on Galaxy Score as an example.


A brief description of Galaxy Score:

Galaxy score™ is a combination of four metrics — the price score, social impact score, average sentiment, and correlation rank. It measures the relative price appreciation between current and previous interval MACD (moving average convergence divergence), engagement and impact across various social media platforms, average sentiment classified by our machine-learning engines, and correlation of social media volumes and spam to price and volume. The metrics are aggregated and normalized to a scale of 100.


To understand more about why you would use Galaxy Score to guide your trades, check out the Trading Parrot videos illustrating LunarCrush and 3Comma bots work together. These videos will help you figure out the best ways to work with LunarCrush data and use them to build automation into your trading in 3Commas.


Using Galaxy Score, a trader could identify the top crypto opportunities for several assets and trigger trades on the 3Commas platform. You first retrieve the top opportunities via the LunarCrush APIcoins endpoint and then use the smart_trades endpoint on the 3Commas API to act. Before you decide on the action that you want to take, make sure that the action is available on the 3Commas API.


Before you start, you need:

Writing a Simple Python Script to View Coin Data

We’ll be using Python as our scripting language, but you can see several other language examples in the LunarCrush documentation. For brevity, we’ll return only the top 2 coins and look at the JSON output. You can, of course, pull the top 10 or top 20 coins and review them.


The sort and limit parameters can be used on the coin endpoint to perform the query. Since the galaxy_score sort value sorts with the most popular asset first, you can use it with a limit value of “2” to get the top two assets. The following code snippet uses the API to pull the top 2 coins based on their Galaxy Score and prints them to the screen:


import requests
import json


# Define the URL for lunarcrush and set the authorization header. 
# This header is standard when passing keys to an API and must be present to
# successfully execute queries against the API.

apiUrl = "https://lunarcrush.com/api3/coins?sort=galaxy_score&limit=2"
headers = {"Authorization":"Bearer <your_api_keys>"}
response = requests.request("GET", apiUrl, headers=headers)

print(json.dumps(response.json(), indent=2))

The print command displays:


{
"data": [
    {
      "id": 72743,
      "s": "SUZUME",
      "n": "Shita-Kira Suzume",
      "p": 3.8585999e-06,
      "v": 400666.64,
      "pc": -8.82,
      "pch": -3.15,
      "mc": 0,
      "gs": 68,
      "gs_p": 48,
      "ss": 824467,
      "as": 3.354166666666666,
      "sv": 1261,
      "c": 79,
      "sd": 0.2051035394961736,
      "d": 0,
      "acr": 750,
      "acr_p": 30,
      "tc": 1660255200,
      "categories": "defi,erc20,meme"
    },
    {
      "id": 483,
      "s": "BOMB",
      "n": "BOMB",
      "p": 0.21063406,
      "v": 131720.37,
      "pc": 8.72,
      "pch": -0.88,
      "mc": 172195,
      "gs": 67,
      "gs_p": 36.5,
      "ss": 186953,
      "as": 3.7999999999999994,
      "sv": 60,
      "c": 5,
      "sd": 0.005897728801816271,
      "d": 1.7071053333987078e-05,
      "acr": 160,
      "acr_p": 428,
      "tc": 1567036800,
      "categories": ""
    }
  ]
}


The gs value is the Galaxy Score metric, so as you can see SUZUME is the first asset listed with a Galaxy Score of 68. BOMB is the next asset with a Galaxy Score of 67. We can step through each of these values to act as the 3Commas API.


The first step is to add a loop to the code to iterate through each asset. In this example, the name of the asset and its Galaxy Score are printed but will be replaced with 3Commas API action calls:


import requests
import json

# Define the URL for lunarcrush and set the authorization header. 
# This header is standard when passing keys to an API and must be present to
# successfully execute queries against the API.

apiUrl = "https://lunarcrush.com/api3/coins?sort=galaxy_score&limit=2"
headers = {"Authorization":"Bearer <your_api_keys>"}
response = requests.request("GET", apiUrl, headers=headers)
res = response.json()

print(json.dumps(response.json(), indent=2))


# Loop through each coin in the response
for coin in res['data']:
    print("name: ", coin['s'])
    print("galaxy score: ", coin['gs'])


Now that you’ve tested the LunarCrush API, you can add code to act on the 3Commas API. We’re doing a simple trade in the following code with the new 3Commas code bolded:


import requests
import json
import os
from py3cw.request import Py3CW

p3cw = Py3CW(
key='<your_3commas_key>',
secret='<your_3commas_secret>',
request_options={
'request_timeout': 10,
'nr_of_retries': 1,
'retry_status_codes': [502]
}
)


# Define the URL for lunarcrush and set the authorization header. 
# This header is standard when passing keys to an API and must be present to
# successfully execute queries against the API.

apiUrl = "https://lunarcrush.com/api3/coins?sort=galaxy_score&limit=2"
headers = {"Authorization":"Bearer <your_api_keys>"}
response = requests.request("GET", apiUrl, headers=headers)
res = response.json()


# Loop through each coin in the response
for coin in res['data']:
    # Send the coin information to 3Commas and make a purchase
    error, data = p3cw.request(
        entity='smart_trades_v2',
        action='new',
        payload={
            "account_id": your_account_id,
            "pair": "<your_pair>",
            "instant": "true",
            "position": {
                "type": "buy",
                "units": {
                    "value": "0.01"
                },
                "order_type": "market"
            }
        }
    )


In this code snippet, the p3cw 3Commas wrapper simplifies all the calls to the API. The “entity” can be one of several listed in the wrapper documentation. In each of the entity helpers, you can read how to send a payload (command) to the API to act. In this example, trade is done using the smart_trades_v2 endpoint, but you can also make changes to a bot, your account, deals, and the marketplace.


You can add a filter to drill down even further. It’s not enough to pull only coins with the highest Galaxy Score for some traders. You might want a coin with a high trading volume, market cap, or one within a specific category. This filter would be programmed in your Python script, so it takes some extra development. Let’s take the script and edit it to only work with coins in the NFT category.


import requests
import json
import os
from py3cw.request import Py3CW

p3cw = Py3CW(
key='<your_3commas_key>',
secret='<your_3commas_secret>',
request_options={
'request_timeout': 10,
'nr_of_retries': 1,
'retry_status_codes': [502]
}
)


# Define the URL for lunarcrush and set the authorization header. 
# This header is standard when passing keys to an API and must be present to
# successfully execute queries against the API.

apiUrl = "https://lunarcrush.com/api3/coins?sort=galaxy_score&limit=50"
headers = {"Authorization":"Bearer <your_api_keys>"}
response = requests.request("GET", apiUrl, headers=headers)
res = response.json()


# Loop through each coin in the response
for coin in res['data']:
    # The chosen filter is to only work with coins in the NFT category, 
    # so eliminate anything that isn't an NFT
    # You can use any filter you want from the LunarCrush categories
    if coin['categories'].find('nft') > -1:
        # Send the coin information to 3Commas and make a purchase
        error, data = p3cw.request(
            entity='smart_trades_v2',
            action='new',
            payload={
                "account_id": your_account_id,
                "pair": "<your_pair>",
                "instant": "true",
                "position": {
                    "type": "buy",
                    "units": {
                        "value": "0.01"
                    },
                    "order_type": "market"
                }
            }
        )


The newly added lines of code are bolded. It determines if the asset is in the NFT category before processing it on the 3Commas API. You can filter trades even further using any of the data points returned by LunarCrush. Here is the output using a coin with its annotations to describe values you’ll find in the API:


  {
      id: 11880 LunarCrush internal ID for the asset,
      s: RAY symbol,
      n: Raydium Protocol name,
      p: 0.65456285 Price,
      v: 27393233.82 Volume (USD),
      pc: 6.9 Percent change (24 Hours),
      pch: -1.04 Percent change (1 Hour),
      mc: 87523220 Market cap,
      gs: 70.5 Galaxy ScoreTM,
      gs_p: 40.5 Galaxy ScoreTM previous 24h,
      ss: 59960 Social score/engagement,
      as: 4.029166666666666 Average sentiment - using a scoring system from 1 to 5 with 1 being very bearish and 5 being very bullish,
      sv: 63 Social volume/mentions,
      c: 14 Social contributors (24 hours),
      sd: 0.014487283164701735 Social dominance,
      d: 0.008159268441644609 Market dominance,
      acr: 198 ALTRankTM,
      acr_p: 515 ALTRankTM previous 24h,
      tc: 1619553600 Time created,
      categories: defi, solana,
        
    }


LunarCrush returns the highest-scoring datasets by default, meaning that the default sort order is the highest Galaxy Score coin to the lowest Galaxy Score coin. The limit is set to 50 in this latest example, so the top 50 coins based on Galaxy Score are returned. You may at some point want to get the lowest value Galaxy Score coins, so you can reverse the sort order using the “desc” parameter. Here is the same code, but in descending order:


import requests
import json
import os
from py3cw.request import Py3CW

p3cw = Py3CW(
key='<your_3commas_key>',
secret='<your_3commas_secret>',
request_options={
'request_timeout': 10,
'nr_of_retries': 1,
'retry_status_codes': [502]
}
)


# Define the URL for lunarcrush and set the authorization header. 
# This header is standard when passing keys to an API and must be present to
# successfully execute queries against the API.

apiUrl = "https://lunarcrush.com/api3/coins?sort=galaxy_score&limit=50&desc=1"
headers = {"Authorization":"Bearer <your_api_keys>"}
response = requests.request("GET", apiUrl, headers=headers)
res = response.json()


# Loop through each coin in the response
for coin in res['data']:
    # The chosen filter is to only work with coins in the NFT category, 
    # so eliminate anything that isn't an NFT
    # You can use any filter you want from the LunarCrush categories
    if coin['categories'].find('nft') > -1:
        # Send the coin information to 3Commas and make a purchase
        error, data = p3cw.request(
            entity='smart_trades_v2',
            action='new',
            payload={
                "account_id": your_account_id,
                "pair": "<your_pair>",
                "instant": "true",
                "position": {
                    "type": "buy",
                    "units": {
                        "value": "0.01"
                    },
                    "order_type": "market"
                }
            }
        )


Try out both code snippets to see the difference in your dataset. We limit it to 50 coins, but you can leave the parameter empty to return all coins or limit your dataset even further.**
**

While this is a simple script, you can get much more creative and complex by writing your bots in the language of your choice. The two APIs offer a flexible way to control your trade activity to optimize your profits and lower your overhead. For example, you could write a script that continually polls the LunarCrush API for the best opportunities and automatically performs trades without lifting a finger.


Lower Your Research and Immediately Capitalize on Asset Opportunities

Building with LunarCrush introduces opportunities that you might not know without hours of research and constant monitoring. Let LunarCrush help you simplify and automate your discovery process, and use it to automate trades against any bot interface.


Check out what’s happening in the market__ now, orsign up to get started.