How to Beat the Stock Market with Maths: A Dual Strategy Approach | Part 2

martin vizzolini
Coinmonks
11 min readSep 14, 2023

--

Introduction

Following our detailed exploration in Part 1, where I explained the dual-strategy approach and the Fourier transform function to detect entry points, I now present the next chapter. Here, the transition from theory to practice showcases the tangible outcomes of our mathematical models and algorithms in the real world. All the trading logic, decisions, and actions are driven by an automated Bot developed in Python.

In this post, we will analyze the result obtained by the bot describing some real scenarios. I am going to present some real results in the last 2 months. I left the futures account to be managed only by the bot, so every trade in the results was made by the logic of the bot strategy.

Methodology

Initially, I had to determine which exchange we would use for our test and which cryptocurrencies would be part of the instances. After analyzing the backtesting results, I chose to work with three distinct exchanges, each operating with different sets and numbers of coins: Binance, Bybit, and Coinex, mainly due to their competitive fees and the wide range of coins compatible with the Bot.

As previously outlined in our strategy, we required two instances to execute our approach: one for Short positions and another for Long positions. To provide a clearer picture, let’s consider the coin configuration we used on the Binance exchange:

For the Long BOT, I selected the following coins: ARPA, XMR, OCEAN, CELO, LTC, ANT, TRX, XRP, OGN, CTXC, NMR, and BAND.

For the Short BOT, my chosen coins were: ARPA, XMR, OCEAN, CELO, LTC, ANT, TRX, XRP, ZEC, EOS, RSR, and REEF.

Certain coins operate in both Long and Short positions simultaneously, while others stick to just one direction, for example, we have set BAND to operate only the Long instance and REEF only for Short positions. This isn’t arbitrary; it’s because not every coin performs optimally in both directions.

For those coins set to operate in both directions, we can illustrate better examples of how the algorithm works and represent it in the same image.

Trades made by the Bot in Long and Short for the coin ANT

The next crucial decision was determining the amount of capital to invest and the size of each purchase order. I decided to start with a balance of 400 USD and set each purchase order at 20 USD and finished the last run with a capital of 750 USD and an order size of 40 USD. As discussed in our previous post, the relationship between the investment capital, the size of the orders, and the number of coins the bot trades with is vital. The profit is closely tied to the appropriate values assigned to these variables.

Ensuring Profits and Controlled Losses

The main strategy is to operate in both directions: both “long” (buying) and “short” (selling). You can get more detailed information about this strategy in the previous post. This strategy can be particularly effective in volatile markets and can offer a way to ensure profits if executed correctly.

Imagine you decide to enter a “long” position at a certain price, expecting the asset to rise in value. Simultaneously, you take a “short” position at a price higher than your “long” entry. If the market moves downward, your “short” position will generate profits, offsetting any potential loss in your “long” position. Conversely, if the market rises, your “long” position will be profitable.

The key here is that since the “short” position was taken at a higher price than the “long” one, any downward price movement will guarantee a net gain, as the profits from the “short” will outweigh the losses from the “long”.

Profit Guarantee When Initiating a Short Position at a Higher Price

However, if the opposite occurs, where a “long” buy is made above the price of a “short”, what we’re essentially guaranteeing is a controlled loss. This means that the potential loss is predetermined and limited to the difference between the two entry points. The algorithm, thanks to the Fourier transform, knows when to close the short and long open positions when it spots a trend change, not just make an exit, but could also make a strategic re-entry jump back in, while the bot operating in the profitable direction cashes out. At this point, our best scenario is to have a volatile market.

Controlled loss

But, what’s the reason to maintain open positions on both sides, the reason I decided not to close the positions even when both directions are profitable, is because we can lose potential big profits.

To illustrate, consider the following example: The bot executed two trades for the ARPA coin, one in a Long position (represented by the green line) and the other in a Short position (indicated by the red line). As I have tested so far, the profits generated are significantly better when the bot’s long and short instances operate independently.

Long and Short bot instances maximizing profits.
Order history of the Long and Short trades made by the bot.

Trading in both directions can be an effective strategy for securing profits under various market conditions while also ensuring controlled losses when necessary. The volatility of the market is our best friend for our strategy. The average of these trades in both directions is what makes the bot profitable.

ANT Coin Trading Analysis Over a 10-Day Period

Given that the strategy operates across various coins, would be a very large post if we get a detail of each trade and each coin, so we will analyze some of them with the goal of showing the logic behind and how the trades are made.

The following chart illustrates the Bot’s trades over a 10-day period for the ANT coin: red lines represent Short trades, while green ones denote Long trades.

Graphic of order history for ANT in a period of 10 days of trades
Order history for ANT in a period of 10 days of trades

In this period we can identify three closed long trades, one closed short trade, and one open short trade. By examining the transaction history, we can precisely compute the profit from each transaction:

Individual Profit Trades

Long 1 (Open Long -> Close Long)

Purchase: 5.7 units at 3.995 USDT = 22.7715 USDT 
Sale: 5.7 units at 4.090 USDT = 23.313 USDT
Profit: 23.313–22.7715 = 0.5415 USDT
Percentage gain: (0.5415 / 22.7715) * 100 = 2.38%

Long 2 (Open Long -> Close Long)

Purchase: 5.4 units at 4.250 USDT = 22.95 USDT 
Sale: 5.4 units at 4.340 USDT = 23.436 USDT
Profit: 23.436–22.95 = 0.486 USDT
Percentage gain: (0.486 / 22.95) * 100 = 2.12%

Short 1 (Open Short -> Close Short)

Short Sale:
5.3 units at 4.280 USDT = 22.684 USDT
10.1 units at 4.520 USDT = 45.652 USDT
Total from short sale: 68.336 USDT
Purchase to close short position: 15.4 units at 4.060 USDT = 62.524 USDT
Profit: 68.336–62.524 = 5.812 USDT
Percentage gain: (5.812 / 68.336) * 100 = 8.51%

Long 3 (Open Long -> Close Long)

Purchase: 5.3 units at 4.335 USDT = 22.9755 USDT 
Sale: 5.3 units at 4.420 USDT = 23.426 USDT
Profit: 23.426–22.9755 = 0.4505 USDT
Percentage gain: (0.4505 / 22.9755) * 100 = 1.96%

Short 2 (Open Short)

Short Sale: 5.5 units at 4.155 USDT = 22.8525 USDT 
This transaction has not yet been closed

It’s worth noting that during this timeframe, the Bot consistently secured profits from every transaction in both the Long and Short instances.

| Operation   | size (USDT) | Profit (USDT) | Profit (%) |
|-------------|-------------|---------------|------------|
| Long | 22.7715 | 0.5415 | 2.38% |
| Long | 22.9500 | 0.486 | 2.12% |
| Short | 68.336 | 5.812 | 8.51% |
| Long | 22.9755 | 0.4505 | 1.96% |
| Open Short | 22.8525 | Not Closed | N/A |

We aim for profits with every coin, but let’s be clear: it’s not always going to happen. Sometimes we win, sometimes we lose. While we can’t always avoid losing trades, we can certainly manage the magnitude of our losses.

In the following example, we will explore other trades made by the bot, including those where the outcomes were not profitable.

XRP Coin Trading Analysis Over a 20-Day Period

In this example of trading operated by the bot for the coin XRP in a period of 20 days, the bot made three Long trades and three Short trades.

Graphic of order history for XRP in a period of 20 days of trades
Order history for XRP in a period of 20 days of trades

Individual Profit Trades

Long 1 (Open Long -> Close Long)

Purchase: 32 units at 0.6996 USDT = 22.3872 USDT 
Sale: 32 units at 0.7155 USDT = 22.896 USDT
Profit: 22.896–22.3872 = 0.5088 USDT
Percentage gain: (0.5088 / 22.3872) * 100 = 2.27%

Long 2 (Open Long -> Open Long(2x) -> Close Long)

Purchase 1: 32 units at 0.7130 USDT = 22.816 USDT 
Purchase 2: 69 units at 0.6621 USDT = 45.6849 USDT
Total Purchase: 22.816 + 45.6849 = 68.5009 USDT
Sale: 101 units at 0.6075 USDT = 61.3575 USDT
Profit: 61.3575–68.5009 = -7.1434 USDT (loss)
Percentage loss: (-7.1434 / 68.5009) * 100 = -10.42%

Short 1 (Open Short -> Close Short)

Short Sale: 32 units at 0.7074 USDT = 22.6368 USDT 
Purchase to Close: 32 units at 0.6826 USDT = 21.8432 USDT
Profit: 22.6368–21.8432 = 0.7936 USDT
Percentage gain: (0.7936 / 21.8432) * 100 = 3.63%

Short 2(Open Short -> Close Short)

Short Sale: 34 units at 0.6658 USDT = 22.6372 USDT 
Purchase to Close: 34 units at 0.6311 USDT = 21.4574 USDT
Profit: 22.6372–21.4574 = 1.1798 USDT
Percentage gain: (1.1798 / 21.4574) * 100 = 5.50%

Short 3 (Open Short -> Close Short)

Short Sale: 36 units at 0.6257 USDT = 22.5252 USDT 
Purchase to Close: 36 units at 0.6076 USDT = 21.8736 USDT
Profit: 22.5252–21.8736 = 0.6516 USDT
Percentage gain: (0.6516 / 21.8736) * 100 = 2.98%

Long 3 (Open Long -> Close Long)

Purchase: 135 units at 0.5897 USDT = 79.6095 USDT 
Sale: 135 units at 0.4275 USDT = 57.7125 USDT
Profit: 57.7125–79.6095 = -21.897 USDT (pérdida)
Percentage loss: (-21.897 / 79.6095) * 100 = -27.51%

For this iteration, we had two trades that incurred losses, the bot decided to close those positions based on the stop-loss strategy that guaranteed us correct risk control.

| Operation   | Size (USDT) | Profit (USDT) | Profit (%) |
|-------------|-------------|---------------|------------|
| Long | 22.3872 | 0.5088 | 2.27% |
| Long | 68.5009 | -7.1434 | -10.42% |
| Short | 21.8432 | 0.7936 | 3.63% |
| Short | 21.4574 | 1.1798 | 5.50% |
| Short | 21.8736 | 0.6516 | 2.98% |
| Long | 79.6095 | -21.897 | -27.51% |

What we’re observing is the trading percentage change for each single trade, for example, in the last trade It doesn’t mean we lost 27.51% of our capital, It just means that particular trade went 27% down based on the capital thrown into that order size. That’s the bot’s stop-loss in action.

We hit losses in about 20–25% of our moves, but the other 75–80%? Those are where we make our money back. We’re playing the field with multiple coins and instances. So, a 27.51% dip in one deal is relatively minor when considering our total bot capital.

However, it’s essential to understand that the bot isn’t some magic money machine, we play against the Maths and the Statistics, so It’s imperative to be well-prepared for any unfavorable scenario.

Binance Performance: A Breakdown of Bot’s Profit and Loss

Profit and Loss Analysis

What are the results when we operate multiple coins? What we see here is the daily total result in the Binance exchange, the green bars indicate the Bot made a profit on that day, and the red bar indicates the bot incurred a loss. This represents an average of all closed trades for that day.

PNL from dates: 2023–07–12 to 2023–09–11 (two months)
Cumulative PNL in the last two months

The net profit stands at 90.65 USD, achieved with a win rate of 76.19%. This means that out of all trading days, profits were made on 48 days and losses on 15 days. On average, the profit per winning day was 3.49 USD, while the average loss per losing day was 5.13 USD. A key metric to highlight is the Profit/Loss Ratio, which is 0.68. This provides a snapshot of the effectiveness and efficiency of a trading strategy.

| Metric            | Value       |
|-------------------|-------------|
| Total Profit | 167.66 USD |
| Total Loss | 77.01 USD |
| Net Profit/Loss | 90.65 USD |
| Win Rate | 76.19 % |
| Winning Days | 48 Days |
| Losing Days | 15 Days |
| Breakeven Days | 0 Days |
| Average Profit | 3.49 USD |
| Average Loss | 5.13 USD |
| Profit/Loss Ratio | 0.68 |

We can see the correlation between the daily and the cumulative PNL. We can have some days when the bot got losses, but our goal is to have the cumulative PNL in a trend positive in the long term:

Days incurring in losses
Cumulative PNL in the Days incurring losses

Quantity of Trades made by the BOT

In the last two months, the bot made around 600 operations including Long and Short positions, It’s an average of 5 trades per day for both instances each.
Not all of the coins have a similar number of operations, It will depend on the market and the volatility of that coin in the period of time, so in this example, for different coins, we can get different quantities of operations:

XRP: 84 operations
XMR: 36 operations

One of the most TODO’s on my list is to improve the profit calculations, also the profits will depend on the leverage of the trade positions assigned by the bot. For the examples explained before I’ve stuck to a 2X leverage. I think we could push it to 3X without increasing our risk, but that would be a matter of investigation for the next stage.

For now, check out the PNL stats from Binance to get a rough idea of the kind of profit percentages this bot can obtain.

The bot has been actively operating on Coinex and Bybit as well, utilizing different coins, initial capital, and different initiation dates and the results have remained notably consistent. It’s worth noting that some of the visual data you’ve seen comes from Bybit because Binance only flashes the last 15 days of trade operations in the graphic.

Conclusions

One remarkable aspect of the bot’s performance is its ability to avoid significant losses. Even on days when losses occurred, they were typically a minor setback following a previous profit, and my overall capital never experienced substantial declines. I’m genuinely impressed by the bot’s confidence and risk management capabilities.

My initial objective was to create a bot that could preserve capital, and I’m delighted with the results.

If you have any questions or would like me to provide more detailed explanations of specific features, please don’t hesitate to ask. Your feedback and comments are highly valued.

Thank you!

Link to the first part of this Strategy: https://medium.com/p/2cfbf2a6558f

--

--