Graphical Martingale Trading Strategy
Tags: trading, strategy, fmzquant, cryptocurrency
Published: 2024-06-18 07:38:56

## Summary
Strictly speaking, Martingale is a method of position management. It can be traced back to the eighteenth century and has been enduring for hundreds of years. There are still many martingale or similar strategies. People have mixed praises and criticisms about this strategy. This section we use FMZ platform to demonstrate it in a graphical way.

## What is martingale
Martingale originated in France, literally translated in English: martegal, originally referred to the harness that controls the carriage. Martingale later represented a gambling strategy. It was initially used in roulette gambling and gradually extended to financial transactions. Until today, the shadow of Martingale can be seen in stocks, futures, and foreign exchange. The reason for its endurance is that, theoretically, this is a strategy that never loses money.

## Forward Martingale
The secret of never losing money is to double the bet every time you lose money, and return the bet to the original unit after any win. No matter how many times you lose before winning, as long as the probability allows the gambler to win once, not only will it be able to win back all previous losses, but also the profit of one bet. Martingale has created many profit miracles and losses in the financial market.

Taking a coin toss as an example, the probability of the front and back is about 50%. The number of consecutive fronts or backs starts to decrease with a 50% probability, which means that in any coin toss, the probability of a heads is 50%, the probability of 2 consecutive positives is 25%, the probability of 3 consecutive positives is 12.5%, and so on.

If the initial bet is 1 , the bet for consecutive losses is increased by a multiple of 2, that is: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, etc., until you win, one round is finished, so each round can win 1. Although in theory, Martingale can never lose money, but as a series of losses occur, the size of the bet will increase exponentially. In order to avoid the use of this strategy by well-funded gamblers, almost all casinos have a maximum betting limit for each game.

### Verify the forward martingale with code
```
/*backtest
start: 2020-01-01 00:00:00
end: 2020-01-02 00:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_CTP","currency":"FUTURES"}]
*/

var chart = {
    __isStock: true,
    tooltip: {
        xDateFormat: '%Y-%m-%d %H:%M:%S, %A'
    },
    title: {
        text: 'Money curve'
    },
    rangeSelector: {
        buttons: [{
            type: 'hour',
            count: 1,
            text: '1h'
        }, {
            type: 'hour',
            count: 2,
            text: '3h'
        }, {
            type: 'hour',
            count: 8,
            text: '8h'
        }, {
            type: 'all',
            text: 'All'
        }],
        selected: 0,
        inputEnabled: false
    },
    xAxis: {
        type: ''
    },
    yAxis: {
        title: {
            text: ''
        },
        opposite: false,
    },
    series: [{
        name: "",
        id: "",
        data: []
    }]
}; // Drawing object


// Strategy entry function
function main() {
    var ObjChart = Chart(chart);  // Drawing object
    ObjChart.reset();  // Clear the drawing before starting
    var now = 0  // Random times
    var bet = 1
    var maxBet = 0  // Record maximum multiple
    var lost = 0
    var maxLost = 0  // Maximum consecutive losses
    initialFunds = 10000  // Initial fund
    var funds = initialFunds  // Real-time fund
    while (true) {
        if (Math.random() > 0.5) { // 50% win rate
            funds = funds + bet  // Make money
            bet = 1 // Every time you make money, reset the bet multiple to 1
            lost = 0
        } else {
            funds = funds - bet // Lose money
            bet = bet * 2 // Double the bet multiple if it fails
            lost++
        }
        if (bet > maxBet) {
            maxBet = bet  // Calculate the maximum multiple
        }
        if (lost > maxLost) {
            maxLost = lost  // Calculate the number of consecutive losses
        }
        ObjChart.add([0, [now, funds]])  // Add drawing data
        ObjChart.update(chart)  // Drawing
        now++  // Random times plus 1
        if (funds < 0) {  // If bankruptcy ends the proceedings
            return Log("Initial fund:" + initialFunds + "Random times:" + now   + "Maximum consecutive losses:" + maxLost  + "Maximum multiples:" + maxBet + "Final fund:" + funds)
        }
    }
}
```
## Test Results

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v8o54k86nzu7pzshv90h.png)

## Backward martingale
Contrary to the forward martingale, the reverse martingale is to double the bet every time you win, and return the bet to the initial unit when you lose money. This is an extension of the Martingale strategy. In theory, this strategy is more suitable for use in trending markets, because the operation with the trend has a high success rate. The increase in the success rate is accompanied by the excess returns obtained by gradually increasing positions.

### Verify the Backward martingale with code
```
/*backtest
start: 2020-01-01 00:00:00
end: 2020-01-02 00:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_CTP","currency":"FUTURES"}]
*/

var chart = {
    __isStock: true,
    tooltip: {
        xDateFormat: '%Y-%m-%d %H:%M:%S, %A'
    },
    title: {
        text: 'Money curve'
    },
    rangeSelector: {
        buttons: [{
            type: 'hour',
            count: 1,
            text: '1h'
        }, {
            type: 'hour',
            count: 2,
            text: '3h'
        }, {
            type: 'hour',
            count: 8,
            text: '8h'
        }, {
            type: 'all',
            text: 'All'
        }],
        selected: 0,
        inputEnabled: false
    },
    xAxis: {
        type: ''
    },
    yAxis: {
        title: {
            text: ''
        },
        opposite: false,
    },
    series: [{
        name: "",
        id: "",
        data: []
    }]
}; // Drawing object


// Strategy entry function
function main() {
    var ObjChart = Chart(chart);  // Drawing object
    ObjChart.reset();  // Clear the drawing before starting
    var now = 0  // Random times
    var bet = 1
    var maxBet = 0  // Record maximum multiple
    var lost = 0
    var maxLost = 0  // Maximum consecutive losses
    initialFunds = 10000  // Initial fund
    var funds = initialFunds  // Real-time fund
    while (true) {
        if (Math.random() > 0.5) { // 50% win rate
            funds = funds + bet  // make money
            bet = bet * 2 // Double the bet multiple if you make money
            lost = 0
        } else {
            funds = funds - bet // loss money
            bet = 1 // Every time you lose money, reset the bet multiple to 1
            lost++
        }
        if (bet > maxBet) {
            maxBet = bet  // Calculate the maximum multiple
        }
        if (lost > maxLost) {
            maxLost = lost  // Calculate the number of consecutive losses
        }
        ObjChart.add([0, [now, funds]])  // Add drawing data
        ObjChart.update(chart)  // Drawing
        now++  // Random times plus 1
        if (funds < 0) {  // If bankruptcy ends the proceedings
            return Log("Initial fund:" + initialFunds + "Random times:" + now   + "Maximum consecutive losses:" + maxLost  + "Maximum multiples:" + maxBet + "Final fund:" + funds)
        }
    }
}
```
## Test Results

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jn7a3v9qbpnj3o5rl0yo.png)

## Martingale's application in the futures market
Although there is no limit on the maximum order volume in the futures market, unlike casinos, the rise and fall of futures is not a completely random bet. The real financial trading market is more complicated than casinos. If the Martingale strategy is used in futures trading, once the market moves in the opposite direction of the trend market, as the market develops, the doubled position will increase and the risk will increase. Then for traders who want to use Martingale strategy for the futures market, at least three problems need to be solved:

1. Starting position
2. Adding position multiples
3. Adding position distance

The initial position needs to be determined according to your capital amount, that is, calculate the maximum number of consecutive losses that the capital can withstand before trading. If the initial position is too high, it will cause an excessive amount of funds to be invested after each doubling of the position. In addition, too high a position increase multiple will cause the same problem. Martingale defaults to double position increase. If it is set to 3 times increase position, the speed of bankruptcy will be faster, but if it is set to 1.5 times increase position, it will appear Another result. The last thing to consider is the distance to increase the position. For example, opening a long position at 5000 price, adding a position when the price drops 15 pips, and adding a position when the price drops 30 pips, is also different. This completely depends on the trader's risk tolerance and trading habits preferences.

From: https://www.fmz.com/digest-topic/5928