0bps

Strategy vault / Other

Paul The Gambler Lévy Gold Edition

Python strategy by FawkesPan.

PythonOtherRSI
Author
FawkesPan
Complexity
Intermediate · 227 lines
Parameters
8

Futures Gambler Strategy

If the direction is wrong, automatically reverse and double the position

Live trading will lose all money!!!

Live trading will lose all money!!!

Live trading will lose all money!!!

Live trading will lose all money!!!

Parameters

NameDefaultWhat it controls
STOP_LOSS0.015Stop loss distance
TAKE_PROFIT0.03Take Profit Distance
START_SIZEtrueInitial position
RISK_LIMIT1025Maximum position
LEVERAGE_RATE20Leverage Size
CONTRACT_TYPEthis_weekContract Type
DELAY30Refresh interval
AMP2Reverse multiple

Source Python



#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# encoding: utf-8
#
#  Paul "The Gambler" Lévy.
#
# Copyright 2018 FawkesPan
# Contact : [email protected] / Telegram@FawkesPan
#
# Do What the Fuck You Want To Public License
#

import random
import talib
import numpy as np
from math import *

Account = {}
Ticker = {}
Records = {}
LPosition = 0
SPosition = 0
Positions = {}
TotalLoss = 0
TotalWin = 0
FullLoss = 0
MaxPosition = 0
TotalLongs = 0
TotalShorts = 0

def cancelAllOrders():
    orders = exchange.GetOrders()
    for order in orders:
        exchange.CancelOrder(order['Id'], order)
    return True

def updateMarket():
    global Ticker
    global Records

    Ticker = exchange.GetTicker()
    Records = exchange.GetRecords()

    return True

def getTAFormat(Records):
    Close = []
    for item in Records:
        Close.append(item['Close'])

    return np.array(Close)

def updateAccount():
    global Account
    global LPosition
    global SPosition
    global Positions
    global MaxPosition

    LPosition = 0
    SPosition = 0
    Positions = {}
    for item in exchange.GetPosition():
        if item['MarginLevel'] == LEVERAGE_RATE:
            if item['Type'] == 1:
                Positions['Short'] = item
                SPosition += item['Amount']
            else:
                Positions['Long'] = item
                LPosition += item['Amount']
        MaxPosition = max(MaxPosition, SPosition, LPosition)

    Account = exchange.GetAccount()

    return True

def updatePositions():
    global TotalWin
    global TotalLoss
    global FullLoss

    opened = False

    try:
        Long = Positions['Long']['Amount']
        LongEntry = Positions['Long']['Price']
        Current = Ticker['Sell']

        StopLoss = LongEntry * (1-STOP_LOSS)
        TakeProfit = LongEntry * (1+TAKE_PROFIT)

        if Current > TakeProfit:
            Risked = True
            Log('Long position reaches preset take-profit price. #0000FF')
            TotalWin+=1
            Log('Total number of times to take profit: ', TotalWin, ' Total number of stop losses: ', TotalLoss, ' Complete stop loss times: ', FullLoss, ' Maximum position held: ', MaxPosition, ' Total open long: ', TotalLongs, ' Total short opening: ', TotalShorts)
            coverLong(Long, True)
        if Current < StopLoss:
            Risked = True
            Log('Long position reaches preset stop-loss price. #FF0000')
            TotalLoss+=1
            Log('Total number of times to take profit: ', TotalWin, ' Total number of stop losses: ', TotalLoss, ' Complete stop loss times: ', FullLoss, ' Maximum position held: ', MaxPosition, ' Total open long: ', TotalLongs, ' Total short opening: ', TotalShorts)
            coverLong(Long, True)
            if Long*AMP < RISK_LIMIT:
                openShort(Long*AMP, True)
            else:
                FullLoss+=1
                Log('Exceeds the maximum allowed position and stops opening positions.. #FF0000')
                Log('Total number of times to take profit: ', TotalWin, ' Total number of stop losses: ', TotalLoss, ' Complete stop loss times: ', FullLoss, ' Maximum position held: ', MaxPosition, ' Total open long: ', TotalLongs, ' Total short opening: ', TotalShorts)

        opened = True
    except KeyError:
        pass

    try:
        Short = Positions['Short']['Amount']
        ShortEntry = Positions['Short']['Price']
        Current = Ticker['Buy']

        StopLoss = ShortEntry * (1+STOP_LOSS)
        TakeProfit = ShortEntry * (1-TAKE_PROFIT)

        if Current < TakeProfit:
            Risked = True
            Log('Short position reaches preset take-profit price. #0000FF')
            TotalWin+=1
            Log('Total number of times to take profit: ', TotalWin, ' Total number of stop losses: ', TotalLoss, ' Complete stop loss times: ', FullLoss, ' Maximum position held: ', MaxPosition, ' Total open long: ', TotalLongs, ' Total short opening: ', TotalShorts)
            coverShort(Short, True)
        if Current > StopLoss:
            Risked = True
            Log('Short position reaches preset stop-loss price. #FF0000')
            TotalLoss+=1
            Log('Total number of times to take profit: ', TotalWin, ' Total number of stop losses: ', TotalLoss, ' Complete stop loss times: ', FullLoss, ' Maximum position held: ', MaxPosition, ' Total open long: ', TotalLongs, ' Total short opening: ', TotalShorts)
            coverShort(Short, True)
            if Short*AMP < RISK_LIMIT:
                openLong(Short*AMP, True)
            else:
                FullLoss+=1
                Log('Exceeds the maximum allowed position and stops opening positions.. #FF0000')
                Log('Total number of times to take profit: ', TotalWin, ' Total number of stop losses: ', TotalLoss, ' Complete stop loss times: ', FullLoss, ' Maximum position held: ', MaxPosition, ' Total open long: ', TotalLongs, ' Total short opening: ', TotalShorts)

        opened = True
    except KeyError:
        pass

    if not opened:
        Log('Haven't opened a position yet, just open any position.')
        RSI = talib.RSI(getTAFormat(Records), timeperiod=14)
        if RSI[-2]<RSI[-1]:
            Log('RSI14: ', RSI[-1],' Opening long position.')
            openLong(START_SIZE, True)
        else:
            Log('RSI14: ', RSI[-1],' Opening short.')
            openShort(START_SIZE, True)

    return True

def openLong(Amount=0, marketPrice=False):
    global TotalLongs

    Amount = floor(Amount)

    TotalLongs+=Amount

    exchange.SetDirection('buy')

    if marketPrice:
        exchange.Buy(Ticker['Sell']*1.01, Amount)
    else:
        exchange.Buy(Ticker['Sell'], Amount)

    return True

def coverLong(Amount=0, marketPrice=False):
    exchange.SetDirection('closebuy')

    if marketPrice:
        exchange.Sell(Ticker['Buy']*0.99, Amount)
    else:
        exchange.Sell(Ticker['Buy'], Amount)

    return True

def openShort(Amount=0, marketPrice=False):
    global TotalShorts

    Amount = floor(Amount)

    TotalShorts+=Amount

    exchange.SetDirection('sell')

    if marketPrice:
        exchange.Sell(Ticker['Buy']*0.99, Amount)
    else:
        exchange.Sell(Ticker['Buy'], Amount)

    return True

def coverShort(Amount=0, marketPrice=False):
    exchange.SetDirection('closesell')

    if marketPrice:
        exchange.Buy(Ticker['Sell']*1.01, Amount)
    else:
        exchange.Buy(Ticker['Sell'], Amount)

    return True

def onTick():
    cancelAllOrders()
    updateMarket()
    updateAccount()
    updatePositions()

    return True

def main():
    exchange.SetContractType(CONTRACT_TYPE)
    exchange.SetMarginLevel(LEVERAGE_RATE)

    while True:
        onTick()
        Sleep(DELAY*1000)

Published by FawkesPan on the FMZ strategy square · last modified 2018-09-28. Collected in the Quant Trading Vault. Unvalidated research: re-test with your own data and costs before trusting it.

Build this with AgenKit

A spec is not a trading system. Paste this into your coding agent and AgenKit runs a specialist team — architecture, test-first build, risk gates, review — with paper trading on by default.

in Claude Code, Cursor, Codex & 4 more
/agenkit build a production-grade trading bot with a backtest engine, risk controls and paper trading by default from strategies/Paul-The-Gambler-Lévy-Gold-Edition.md
  1. npx agenkit install engineering-kit in your project
  2. Paste the command into your agent and approve each phase
  3. Get tests, backtest, risk controls and a paper-trading switch

Understand it first

Before you run this, read the lesson behind the idea and how to backtest it honestly. Specs like this one are the survivors of an unknown number of trials; deflate their results accordingly.

Related specs

esc

Try , , or .

↑↓ move↵ open