Code Pack - pancakeswapbets

PancakeSwap Data Tracking ML and Trading Automation with Edge Detection

Analyse the Trends of PancakeSwap Prediction Market Traders and Find Your Trading Edge

Technologies
python
Themes
crypto
machinelearning
trading
aws
Skill Level
intermediate
Last updated
2023-03-23

What's Inside

As seen on YouTube:

https://youtu.be/k41OBccGqg4.

Time for us to share some valuable data. With that said - want to be clear on the risks first.

Risks

-
Risk 1: PancakeSwap charges fee commissions on trades. This puts you at a significant disadvantage.
-
Risk 2: Crypto transactions on-chain for BSC incur fees. Although small, these work against you materially. Especially if trading small size.
-
Risk 3: PancakeSwap Predictions is a betting platform. Although some traders have done well out of this, even with an edge you can still lose money due to the above two points.

PancakeSwap Predictions is a binary betting platform whereby who ever predicts the price of BNB in the next 5 minutes takes a payout. The payout is determined by the bulls as a ratio of the bears. For example, if each side had the same amount wagered, the payout would be close to 2.0 for both bulls and bears.

The opportunity arises where if we accept that markets largely move randomly at 5 minute timescales (which they do), and we can predict which side will pay out over 2.0 with any sort of edge, we can make a good sum of money so long as fees don’t hurt us (which they do as mentioned above in the risks section).

The developer, Shaun, has posted videos historically on the Crypto Wizards YT channel talking about his vision for a fair trading system across all assets using blockchain with such binary outcomes and feels strongly that blockchain technology can allow us to trade almost entirely ‘feelessly’ once we have the right tech stack and oracles in place. No more stop losses would be necessary and we could even arbitrage against traditional options markets.

Back to the present.

What if you tracked all known information about BNB on a binary trading solution like the above PancakeSwap Predictions? This could look like the following:

-
Tracking all known data at every minute just before each round wins, including the value of bull versus bear trades and the amount of liquidity, prior round payouts etc
-
Gathered over 2000+ trades to analyse with XGBOOST and ML (taught in the Udemy course of Machine Learning Applied to Crypto and Stock Trading)
-
Ran the data and discovered where the edge lies in placing bets
-
Automated trading based on pulling live data at any point in time and executing the trade
This code package allows you to do exactly that.

Disclaimer: The author nor Code Raiders is in any way affiliated with PancakeSwap or PancakeSwap predictions. We make no profits from you exploring or trading on the platform. This material is purely for research and education. By choosing to execute trades, you are doing so at your own risk.

Uses

-
Tracking all known data at every minute just before each round wins, including the value of bull versus bear trades and the amount of liquidity, prior round payouts etc
-
Gathered over 2000+ trades to analyse with XGBOOST and ML (taught in the Udemy course of Machine Learning Applied to Crypto and Stock Trading)
-
Ran the data and discovered where the edge lies in placing bets
-
Automated trading based on pulling live data at any point in time and executing the trade

Requirements

-
You must have read the disclaimer above
-
You must understand models like XGBOOST and what they do. See our Machine Learning Udemy course if this is new to you
-
You must be able to code at least to an intermediate level in Python

START

What you need to get running

Below is the basic software you will need to get started:

-
Python version 3.7 (note that version 3.10.8 and pip version 22.2.2 in development)
-
GitHub working on your machine

Step 1

Download package

Click the download button at the top of this page. Then save the project on your desktop of project folder. Going forward, we will assume a project name as 'myproject'.
However, you may of course name the project folder whatever makes sense for your purpose.

Step 2

Install Python packages

Change directory into your project folder where the code package is saved:

~/myproject

python3 -m venv venv
Activate your virtual environment (MacOS Users)

~/myproject

source venv/bin/activate
Activate your virtual environment (Windows Users)

~/myproject

source venv/Scripts/activate
Install packages

(venv)~/myproject

pip3 install --upgrade pip
pip3 install python-decouple==3.7 web3==5.31.3 xgboost==1.7.4 scikit-learn==1.1.3 pandas==1.5.1
pip3 install matplotlib==3.7.0
pip3 install boto3==1.26.81 graphviz==0.20.1

Note: If any of the above versions do not work on your machine, that should be fine. Just remove the version number and install the latest.

Next, just add your environment variables in a .env file within the project.

You can create one by typing sudo nano .env or just using VS Code to create a .env file.

(venv)~/myproject/.env

DATABASE_NAME=<ONLY_IF_USING_AWS_TIMESTREAM>
DATABASE_TABLE=<ONLY_IF_USING_AWS_TIMESTREAM>
PROVIDER=https://bsc-dataseed1.binance.org:443
CONTRACT_ADDRESS=0x18B2A687610328590Bc8F2e5fEdDe3b582A49cdA
ACCOUNT=0x<YOUR ACCOUNT>
PRIVATE_KEY=0x<YOUR PRIVATE KEY - MAKE SURE TO BEGIN WITH "0x">
WAGER_BNB=0.015 

Step 3

Setup AWS Timestream (Optional)

This step is optional and useful only if you wish to track data live using AWS Timestream.

There is already 2000+ rows of data provided for you, so this is just a bonus. You do not have to follow this step unless you wish to track PancakeSwap data to build your own database.

AWS Timestream was chosen by the developer because it is hugely cost effective. To attempt this route, it is advisable that you have some experience with the tools on AWS. However, you could easily write some code to just save data to a local JSON or csv file should you prefer to use that route. AWS is not essential, but was used and could provide a way to run a system in the cloud which tracks the data whilst you sleep using an EC2 machine so your own laptop and resources would not be essential.

1 - Create an account with AWS

2 - Create an IAM role which provides full access to AWS Timestream

3 - Create an EC2 instance (download Python etc on this)

4 - Attach your IAM role to your EC2 instance. This will enable your EC2 instance to talk with AWS timestream

5 - Create an AWS Timestream database
6 - Create an AWS Timestream table

Note: You do not need to run an EC2 instance. If you have your permissions for AWS set up on your local machine, you can access your Timestream database directly from your local machine. This requires some knowledge on how to set up. Here is a good staring point on AWS.

Step 4

Track data (optional)

The tracking of data (should you have opted to do this) is done in the PancakeTracker folder.

(venv)~/myproject

python3 PancakeTracker/src/main.py

You should see a printout that says “Sleeping for: n” where n represents the number of seconds.

This sleeping factor is because the bot knows how many seconds until the next PancakeSwap prediction round is set to expire, so it waits until the very last moment (with some buffer for safety of 30 seconds) before it captures the data. This is to bring as much information as possible into your data so that the Machine Learning process later on has the best knowledge of the current wagers placed possible on the current round.

Finally once the sleep is over, you will see the JSON object of the information being stored as shown in the video above.

You might also see the following error:

Error: An error occurred (ResourceNotFoundException) when calling the WriteRecords operation: The table ONLY_IF_USING_AWS_TIMESTREAM does not exist.

This is normal. If you did not enter your AWS credentials into the .env file earlier. To store the data in a different way if you opt out of using AWS, you can simply just replace the code in row 44 of the src/func_database.py file with your own code to store the JSON data.

Remember: with all this said, if you get stuck, do not worry as have provided all the data you need regardless to process to the next step. Steps 3 and 4 are just optional for building up your own data as mentioned prior.

Step 5

Machine Learning

The next step in training your model is entirely very simple. All learning and trading happens in the PancakeLearner folder.

Just run the following:

(venv)~/myproject

python3 PancakeLearner/learn/main.py

Once run, note that the learn/img folder contains some images with useful information:

-
The decision tree used by the model
-
The train versus test results for seeing if the model is overfitting (described in the video above)
-
The feature importance of each field in determining how to reach the goal given to the model
The terminal will also print out the following:

Std Deviation %: 2.1 (how much the results can vary)

Avg Accuracy %: 59.4 (average accuracy, not very useful)

Train Precision %: 67.2

Test Precision %: 57.3 (most important metric - out of the data the model did not see or train on, how many did it get right when betting 1)


Results including Training data:
Count: 1265
Win Rate %: 60.2

Results including Test data:
Count: 969
Win Rate %: 57.7

p-value: 0.0 True (whether we can reject the null hypothesis that the test precision was just luck. True means that it is extremely unlikely that this was just luck).

Finally note the code on the learn/main.py file between rows 28 and 33:

# Add percentages
df["bull_perc_1"] = 1 / df["bull_ratio_1"]

# Add Target - Bet on Shorts
df.loc[df["bull_perc_1"].shift(-1) > 0.5, "TARGET"] = 0
df.loc[df["bull_perc_1"].shift(-1) <= 0.5, "TARGET"] = 1

You can see that the model can predict with 57.3% precision whether the payout will favour bears. This is because if there is a high bull ratio, meaning more liquidity is paid up by bulls than bears, then the bull ratio expressed as a percent is less than 0.5 (1 / bull ratio). Our ML model is set up to detect this as is allocated a 1 as the TARGET if the payout will favours bears. The model results show in the Test (unseen data) that the model was right 57.3% of the time.

Be cautious here. There are risks as outlined in the description. Even with this knowledge, you can still stand to lose. Regardless, this is a fantastic edge to have in any market.

Step 6

Placing trades

In order to place trades, please ensure the following:

1 - You are aware of the risks outlined in the description

2 - You will monitor bot performance regardless of confidence in automation (for example that wins are being claimed)

3 - You have your Account and Private Key provided in your .env file. DO NOT SHARE THIS WITH ANYONE

4 - You have some BNB in your account to trade

The trade/trade.py file on row 70 is commented out. This is the line which executes the trade. It is commented out as a safety feature. If you want to activate trading, just uncomment that line:

(venv)~/myproject/PancakeLearner/trade/trade.py

# Determine trade
if pred_over_1 > PROBA_THRESH:
  print("Placing trade...")
  # send_tx("bear") <-- UNCOMMENT THIS HERE on row 70
Just run the following:

(venv)~/myproject

python3 PancakeLearner/trade/trade.py

You can log into PancakeSwap predictions to monitor that the bot has in fact placed a trade. Remember, the bot will sleep until such time as the 30 second window appears to place a trade, so that the timing of the trade is consistent with the timing of the data being tracked for model training.

Step 7

Automating the process

To automate an EC2 or cloud machine to run, you can use CRON. You can do the same on your local machine, but note that if your machine is off, the process will not run.

‘crontab -e’ edits the CRON.

‘crontab -l’ allows you to view your CRON job after you save it.

If for any reason, your cron does not seem to be running, just add ‘output.txt’ after the main.py part. This will save a file and print out whatever the error was as though you are viewing the terminal. For example:

crontab

*/5 * * * * /bin/timeout -s 2 299 python3 myproject/PancakeTracker/learn/main.py  2>&1
…then becomes…

crontab

*/5 * * * * /bin/timeout -s 2 299 python3 myproject/PancakeTracker/learn/main.py >output.txt  2>&1

When automating anything, you may want to check any files being saved and make these absolute paths rather than relative to the project folder.


TRACKING

This will ensure tracking runs every 5 minutes (remember the script will wait until the right moment to capture data).

crontab

*/5 * * * * /bin/timeout -s 2 299 python3 myproject/PancakeTracker/learn/main.py  2>&1

LEARNING

Automate this if you want your model to update automatically each day.

crontab

0 1 * * * /bin/timeout -s 2 300 python3 myproject/PancakeLearner/learn/main.py  2>&1

TRADING

To automate trading, you can run the following. This will run your code every 4 minutes and wait until the right moment to place the trade.

crontab

4-59/5 * * * * /bin/timeout -s 2 300 python3 myproject/PancakeLearner/trade/trade.py  2>&1

CLAIM WINNINGS

To automate claiming your winnings, you can run the following:

crontab

*5 * * * * /bin/timeout -s 2 300 python3 myproject/PancakeLearner/trade/trade_claim.py  2>&1

Claiming will check the last 3 rounds to ensure your winnings are automatically sent back to your wallet.

CONGRATULATIONS

Well done - you made it.

You are free to now adapt the code to your liking. Enjoy!