Coder Social home page Coder Social logo

tudorelu / pyjuque Goto Github PK

View Code? Open in Web Editor NEW
458.0 29.0 89.0 3.59 MB

⚡ Open Source Algorithmic Trading Bot for Python.

License: MIT License

Python 100.00%
trading bot algorithmic-trading python3 strategy plotting binance ccxt cryptocurrencies bitcoin ethereum kucoin okex

pyjuque's Introduction

! This repo has been DEPRECATED, it is not maintained anymore !

.

.

.

.

.

Python Juju Quant Engine

PYJUQUE     (pai-jook) (Py-thon Ju-ju Qu-ant E-ngine)

This project implements the basic functionality required to engage in algorithmic trading. It can be regarded as a starting point for more complex trading bots.

Installation

Expand installation details.

Make sure you have pip installed. To install the latest version run:

pip install -U git+https://github.com/tudorelu/pyjuque

To install an older (stable) version, run:

pip install pyjuque

Should be good to go! Now check out the example section.

Examples

Checkout these examples to get started stratght away: strategy 1, strategy 2. Below are the simplest scripts on how to get started with pyjuque (just code, with comments). Read the next section to understand the thinking behind them.

Backtesting a Strategy.
# Import the Strategy template
from pyjuque.Strategies import StrategyTemplate
# Import the CcxtWrapper to connect to a cryptocurrency exchange (data provider)
from pyjuque.Exchanges.CcxtExchange import CcxtExchange
# Import the Backtester class
from pyjuque.Backtester import Backtester

# Define Momentum Strategy
class MomentumStrategy(StrategyTemplate):
    ### If the last `momentum_period` candles are monotonically increasing, 
    ### it is a long signal, and if they are monotonically decreasing 
    ### it's a short signal.
    def __init__(self, momentum_period=3):
        if momentum_period < 1:
            raise ValueError("momentum_period should be greater than 1.")
        self.momentum_period = momentum_period
        self.minimum_period = max(100, momentum_period)

    # this function computes all long and short signals
    # that happened on this dataframe (df) 
    def setUp(self, df):
        # the signals on the first `momentum_period` candles are false
        # because we don't have enough data yet to compute
        long_signals = [0] * self.momentum_period
        short_signals = [0] * self.momentum_period
        l_df = len(df)
        close = df['close']
        # for the rest of the candles check out if they were monotonically 
        # increasing or decreasing
        for i in range(self.momentum_period, l_df):
            all_increasing = True
            all_decreasing = True
            # Go through the last 'momentum_period' candles 
            # to see if they're all increasing, decreasing, or not
            for j in range(i + 1 - self.momentum_period, i + 1):
                all_increasing = all_increasing and (close[j] > close[j-1])
                all_decreasing = all_decreasing and (close[j] < close[j-1])
            # if they're all increasing it's a long signal
            long_signals.append(int(all_increasing))
            # if they're all decreasing it's a short signal
            short_signals.append(int(all_decreasing))
        self.long_signals = long_signals
        self.short_signals = short_signals
        self.dataframe = df

    # the bot will call this function with the latest data and if this 
    # returns 1, our bot will place a long order
    def checkLongSignal(self, i = None):
        return self.long_signals[i], None

    # if your exit settings contain 'exit on signal', the bot will exit if it 
    # currently has an open order and it receives a short signal 
    # (IE this function returns 1)
    def checkShortSignal(self, i = None):
        return self.short_signals[i], None

# Define the config file
bot_config = {
    'strategy': {
        'class': MomentumStrategy,
        'params': {'momentum_period' : 2}
    },
    'entry_settings' : {
        'trade_amount': 1_000,      # 1_000 Units per trade
        'go_long' : True,           # Go long
        'go_short' : False,         # Don't go short
        'fee': 0.1                  # 0.1% fee per trade
    },
    'exit_settings' : {
        'exit_on_signal': True    # Exit when you receive opposite signal (we're
                                  # in a LONG position and we get SHORT signal)
    }
}

if __name__ == '__main__':
    # Connect to exchange and get data (last 1000 1h candles for BTC/USDT)
    exchange = CcxtExchange('binance', {'enableRateLimit':True})
    df = exchange.getOHLCVHistorical("BTC/USDT", '1h', 1000)
    # Backtest bot on this data given the previously defined parameters
    bt = Backtester(bot_config)
    bt.backtest(df)
    # Show graph 
    bt.get_fig().show()
Running a Bot.
from pyjuque.Bot import defineBot
import time

def customEntryStrategy(bot_controller, symbol):
    # signal = will_moon(symbol)          # bool
    # last_price = get_price(symbol)      # float
    return signal, last_price

## Defines the overall configuration of the bot 
bot_config = {
    'name' : 'my_bot',
    'test_run' : False                    # set to True to run in simulation mode
    'exchange' : {
        'name' : 'binance',
        'params' : {                      # put here any param that ccxt accepts
            'api_key': 'YOUR_API_KEY',
            'secret' : 'YOUR_API_SECRET'
        },
    },
    'symbols' : ['LINK/BTC', 'ETH/BTC'],  # !! all symbols must trade against same coin
                                          # !! IE: [XX/BTC, YY/BTC] OR [AA/EUR, CC/EUR]
    'starting_balance' : 0.0005,          # denominated in the quote asset against which 
                                          # the symbols are trading (BTC in this case)
    'strategy': {
        'custom': True,
        'entry_function': customEntryStrategy,
    },
    'entry_settings' : {
        'initial_entry_allocation': 100,  # 100% of starting_balance goes in every trade
        'signal_distance': 0.3            # upon receiving an entry_signal, entry order
                                          # is placed 0.3% away from market price
    },
    'exit_settings' : {
        'take_profit' : 3,                # take profit 3% above entry orders
        'stop_loss_value': 10             # stop loss 10% below entry orders
    },
}


## Runs the bot in an infinite loop that executes every 60 seconds 
## stoppable from the terminal with CTRL + C
def Main():
    bot_controller = defineBot(bot_config)
    while True:
        try:
            bot_controller.executeBot()
        except KeyboardInterrupt:
            return
        time.sleep(60)


if __name__ == '__main__':
    Main()

Detailed Explanation

Expand bot explanation.
The idea behind this library is to allow you to implement whatever trading strategy you want, without having to worry about how to connect to the different exchanges via apis, or how to place, cancel and keep track of orders. You simply provide the signals and pyjuque does the rest.

There are a number of settings that you define, like what symbols to trade on, how much money to place per trade and what exchange to use. You also get to set exit settings such as a take profit value and a stop loss value. All these settings get specified in a config dict. Below is a complete example of a config dict:

## Defines the overall configuration of the bot 
bot_config = {
    # Name of the bot, as stored in the database
    'name' : 'my_bot',

    # exchange information (fill with your api key and secret)
    'exchange' : {
        'name' : 'binance', # or 'okex'
        'params' : {  # any parameter accepted by ccxt can go here
            'api_key': 'your_api_key_here',
            'secret' : 'your_secret_here',
            # 'password' : 'your_password_here' # if using 'okex'
        },
    },

    # starting balance for bot
    'starting_balance' : 0.0005,

    # symbols to trade on
    # !IMPORTANT! all symbols must trade against the same coin
    # !! IE: [AAA/BTC, BBB/BTC] OR [AAA/USDT, CCC/USDT]
    'symbols' : ['LINK/BTC', 'ETH/BTC'],  

    # strategy class / function (here we define the entry and exit strategies.)
    # this bot places an entry order when 'customEntryFunction' retruns true
    'strategy': { 
       'custom': True,
       'entry_function' : customEntryFunction 
    },

    # when the bot receives the buy signal, the order is placed according 
    # to the settings specified below
    'entry_settings' : {

        # between 0 and 100, the % of the starting_balance to put in an order
        'initial_entry_allocation': 100,

        # number between 0 and 100 - 1% means that when we get a buy signal, 
        # we place buy order 1% below current price. if 0, we place a market 
        # order immediately upon receiving signal
        'signal_distance': 0.3
    },

    # This bot exits when our filled orders have reached a take_profit % above 
    # the buy price, or a stop_loss_value % below it
    'exit_settings' : {

        # take profit value between 0 and infinity, 3% means we place our sell 
        # orders 3% above the prices that our buy orders filled at
        'take_profit' : 3,

        # stop loss value in percent - 10% means stop loss at 10% below our 
        # buy order's filled price
        'stop_loss_value': 10
    },
}

Besides these settings, you need to provide an entry strategy. It can be as simple as a function, or a more complex strategy class. We'll go over the simple example:

# This is our signal function.
# It receives two parameters - the bot_controller,
# which gives us access to the exchange and to the 
# database, and the symbol on which the bot is 
# currently checking entry signals.
#
# It must return two values, a boolean and a number.
# The boolean is the signal, and the number is the 
# latest price of that symbol 
#
def customEntryFunction(bot_controller, symbol):
  # ... do some stuff here ...
  return signal, last_price_of_symbol

The beauty of this is that you can do whatever the heck you want in that custom entry function, because as long as you return a symbol and the latest price, pyjuque will be happy. You can check coins prices and their indicators, the volume on multiple exchanges, different order books, even weather data, twitter feeds or astronomical events.

Here's a complete example of how to get started with pyjuque:

from pyjuque.Bot import defineBot

## This is our signal function for now. 
def customEntryFunction(bot_controller, symbol):
  # ... do some stuff here ...
  return signal, last_price

## Defines the overall configuration of the bot 
bot_config = { ... }

## Runs the bot in an infinite loop, stoppable 
## from the terminal with CTRL + C
def Main():
    bot_controller = defineBot(bot_config)
    while True:
        try:
            bot_controller.executeBot()
        except KeyboardInterrupt:
            return
        time.sleep(60)


if __name__ == '__main__':
    Main()

Upon creating the bot, a database will be created in your computer, keeping track of orders placed. You can run this example and it will work - but you should update customEntryFunction to do some calculations & return true sometimes, because in its current state the bot won't ever make any trades.

Checkout these examples for more info: strategy 1, strategy 2.

Features

Current Features:
  • Long Bot (Placing Buy Orders on Custom Signals)
    • Market, Limit & Stop Loss Orders
    • Automatically Placing Exit Order when Entry Order was fulfilled
    • State Persistance, the bot stores trades locally
  • Binance Local Order Book
  • Plotting Capabilities
  • Simple Defiinitian of Entry Strategy & Exit Rules (via bot_config)
  • State Persistence Using SQLAlchemy, for any flavour of SQL
In Development:
  • Grid Bot
Future Features:
  • Short Bot
  • OCO orders
  • Selling on signals
  • Trailing Stop Loss
  • Multiple Entries

Modules

This library implements the following modules:

Bot Controller

At pyjuque/Engine/BotController.py.

A module which handles the buying and selling of assets, given simple or more advanced rules, allowing us to run a strategy indefinitely.

Through the bot controller you can access the following objects

  • bot_controller.exchange
    • bot_controller.exchange has some methods that are used under the hood by pyjquue, like
      • getOHLCV
      • placeLimitOrder
      • placeMarketOrder
      • etc
  • bot_controller.exchange.ccxt, a ccxt object which uses the credentials you provided in the bot_config
  • bot_controller.session, SQLAlchemy session through which you can query the database
  • bot_controller.bot model, the model of the bot as stored in the db
  • bot_controller.status_printer, a yaspin spinner used for logging

You can also access the following functions

  • bot_controller.executeBot(), which goes through a bot loop of:
    • checking signals on symbols and placing orders if signals are true
    • checking all open orders placed by the bot and updating them, like so:
      • if a buy order was filled it places the subsequent exit order, at a take_profit price above the buy price
      • if the current price is below stop_loss_value for an open buy order, exits using market price
  • bot_controller.log() which allows you to print some stuff to the terminal
  • bot_controller.bot_model.getOrders(bot_controller.session) which allows you to get all orders
  • bot_controller.bot_model.getOpenOrders(bot_controller.session) which allows you to get all open orders

Exchange Connectors

Implementing multiple exchanges with ccxt. Check out implementation at CcxtExchange. Currently implemented:

binance okex

Older (Deprecated):

At pyjuque/Exchanges.

Local Order Book (for Binance)

At pyjuque/Exchanges/BinanceOrderBook.py.

Creates and stores a local order book for the specified symbols. Order Book is updated every second through a websocket connection to the Exchange (currently Binance). Checkout this example.

from pyjuque.Exchanges.BinanceOrderBook import OrderBook

# Initialize & start OrderBook with desired symbols
ob = OrderBook(symbols=['BTC/USDT', 'LTC/USDT'])
ob.startOrderBook()
...
# Get Updated Order Book data at any point in your code 
ordb = ob.getOrderBook()
print(ordb)

{
  'BTC/USDT': {
      'asks': [
          ['13662.31000000', '3.24473100'],
          ['13662.82000000', '0.06815300'],
          ['13663.08000000', '0.00900000'],
          ...
          ['20000.00000000', '95.22325900']
        ],
      'bids': [
          ['13662.30000000', '1.26362900'],
          ['13661.78000000', '0.04395000'],
          ['13661.62000000', '0.01439200'],
          ...
          ['10188.00000000', '1.11546400']
        ],
      'lastUpdateId': 6382686192  # ignore this
  },
  'LTC/USDT': {
      'asks': [ ... ],
      'bids': [ ... ],
      'lastUpdateId': 1521585540  # ignore this
  },
 'counter': 11                    # ignore this
}

Coming Soon

More Exchanges

Binance Futures, Bitmex, Bitfinex, FTX, Bybit. Margin Trading, Market Making, Hyper Parameter Tuning.

Contributing

To contribute simply fork the repo, write your desired feature in your own fork and make a pull request upon finishing. Writing tests is also appreciated.

pyjuque's People

Contributors

dependabot[bot] avatar gabriel-milan avatar physicworld avatar pimpmypixel avatar revmischa avatar tudorelu avatar userneeds-ahe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyjuque's Issues

error on tryExitOrder; cannot place limit order after buy fill due to balance error

Running the bot on multiple symbols. 1m timeframe. After a while all the filled buy orders get this error:

INFO:pyjuque.Engine.BotController:FILLED BUY order on BNB/USDT, try exit.
INFO:pyjuque.Engine.BotController:Error placing order for BNB/USDT:
(<class 'ccxt.base.errors.InsufficientFunds'>, InsufficientFunds('binance Account has insufficient balance for requested action.'), <traceback object at 0x7f9db3739ec0>)

I tried playing around with removing take profit, changing 'signal_distance' to market orders. But the issue remains.

The bot is unable to evaluate stop loss or exit signals after this error occurred for a symbol.

Help is appreciated!

Thanks

TypeError(“'<' not supported between instances of 'numpy.ndarray' and 'str'”)

Hello,
I tried to use the code. (Second strategy).
but I keep getting this error and I just don't know where the problem is.
That is the code:

import time

Imports for the strategy

import pandas_ta as ta

Importing these to be able to run this example

from the main pyjuque folder

from os.path import abspath, pardir, join
import sys
curr_path = abspath(file)
root_path = abspath(join(curr_path, pardir, pardir))
sys.path.append(root_path)

Import for defining the bot

from pyjuque.Bot import defineBot

Import for defining the Strategy

from pyjuque.Strategies import StrategyTemplate

Defines the strategy

class BBRSIStrategy(StrategyTemplate):
""" Bollinger Bands x RSI """
def init(self, rsi_len = 8, bb_len = 100, rsi_ob = 50, rsi_os = 50):
self.rsi_ob = rsi_ob
self.rsi_os = rsi_os
self.bb_len = bb_len
self.rsi_len = rsi_len

    # the minimum number of candles needed to compute our indicators
    self.minimum_period = max(100, bb_len, rsi_len)

# the bot will call this function with the latest data from the exchange 
# passed through df; this function computes all the indicators needed
# for the signal
def setUp(self, df):
    df['rsi'] = ta.rsi(df['close'], self.rsi_len)
    df['lbb'], df['mbb'], df['ubb'], df['bb_width'] = ta.bbands(df['close'], self.bb_len)
    self.dataframe = df

# the bot will call this function with the latest data and if this 
# returns true, our bot will place an order
def checkLongSignal(self, i = None):
    """ if the rsi had a sudden increase this candle or the previous one, 
    and one of the previous three values of the rsi was under the oversold 
    level, and the price just crossed over the lower bollinger band, buy"""
    df = self.dataframe
    if i == None:
        i = len(df) - 1
    if i < 3:
        return False
    if (df["rsi"][i] / df["rsi"][i-1] > 1.2) and \
        (df["rsi"][i-1] < self.rsi_os \
            or df["rsi"][i-2] < self.rsi_os \
            or df["rsi"][i-3] < self.rsi_os):
        if ((df["open"][i] < df["lbb"][i] < df["close"][i]) and \
            (df["open"][i-1] < df["lbb"][i-1] and df["close"][i-1] < df["lbb"][i-1])):
            return True
    if (df["rsi"][i-1] / df["rsi"][i-2] > 1.2) and \
        (df["rsi"][i-1] < self.rsi_os \
            or df["rsi"][i-2] < self.rsi_os \
            or df["rsi"][i-3] < self.rsi_os):
        if (df["close"][i-3] < df["lbb"][i-3] and df["close"][i-2] < df["lbb"][i-2] \
            and df["close"][i-1] > df["lbb"][i-1] and df["close"][i] > df["lbb"][i]):
            return True
    return False

# we don't exit on signal, only on take profit pr stop loss level reached
def checkShortSignal(self, i = None):
    return False

Defines the overall configuration of the bot

bot_config = {
# Name of the bot, as stored in the database
'name' : 'my_bot',

# exchange information (fill with your api key and secret)
'exchange' : {
    'name' : 'binance',
    'params' : {
        'api_key': '...',
        'secret' : '...'
    },
},

# symbols to trade on
'symbols' : ['LINK/BTC', 'ETH/BTC'],

# starting balance for bot
'starting_balance' : 0.0005,

# strategy class / function (here we define the entry and exit strategies.)
# this bot places an entry order when the 'checkLongSignal' function of 
# the strategy below retruns true
'strategy': {
    'class': BBRSIStrategy,
    'params': {
        'rsi_len' : 8, 
        'bb_len' : 100, 
        'rsi_ob' : 50, 
        'rsi_os' : 50
    }
},

# when the bot receives the buy signal, the order is placed according 
# to the settings specified below
'entry_settings' : {

    # between 0 and 100, the % of the starting_balance to put in an order
    'initial_entry_allocation': 100,

    # number between 0 and 100 - 1% means that when we get a buy signal, 
    # we place buy order 1% below current price. if 0, we place a market 
    # order immediately upon receiving signal
    'signal_distance': 0.3
},

# This bot exits when our filled orders have reached a take_profit % above 
# the buy price, or a stop_loss_value % below it
'exit_settings' : {

    # take profit value between 0 and infinity, 3% means we place our sell 
    # orders 3% above the prices that our buy orders filled at
    'take_profit' : 3,

    # stop loss value in percent - 10% means stop loss at 10% below our 
    # buy order's filled price
    'stop_loss_value': 10
},

# will the bot display its status / current performing action in the terminal
'display_status' : True

}

Runs the bot in an infinite loop, stoppable from the terminal with CTRL + C

def Main():
bot_controller = defineBot(bot_config)
while True:
try:
bot_controller.executeBot()
except KeyboardInterrupt:
return

    time.sleep(60)

if name == 'main':
Main()

InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers.

Description
When I run a bot for the first time I am getting this error:

InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'mapped class EntrySettingsModel->entry_settings'. Original exception was: Could not determine join condition between parent/child tables on relationship EntrySettingsModel.bots - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.

Traceback

Traceback (most recent call last):

  File "E:\TradingBot\Tests\Bot\pyjuque\test.py", line 70, in <module>
    main()

  File "E:\TradingBot\Tests\Bot\pyjuque\test.py", line 59, in main
    bot_controller = defineBot(bot_config)

  File "E:\Programs\anaconda3\lib\site-packages\pyjuque\Bot.py", line 75, in defineBot
    bot_controller = _defineTaBot(bot_config)

  File "E:\Programs\anaconda3\lib\site-packages\pyjuque\Bot.py", line 85, in _defineTaBot
    bot_model = session.query(TABotModel).filter_by(name=bot_name).first()

  File "E:\Programs\anaconda3\lib\site-packages\sqlalchemy\orm\session.py", line 1584, in query
    return self._query_cls(entities, self, **kwargs)

  File "E:\Programs\anaconda3\lib\site-packages\sqlalchemy\orm\query.py", line 199, in __init__
    self._set_entities(entities)

  File "E:\Programs\anaconda3\lib\site-packages\sqlalchemy\orm\query.py", line 227, in _set_entities
    self._set_entity_selectables(self._entities)

  File "E:\Programs\anaconda3\lib\site-packages\sqlalchemy\orm\query.py", line 258, in _set_entity_selectables
    ent.setup_entity(*d[entity])

  File "E:\Programs\anaconda3\lib\site-packages\sqlalchemy\orm\query.py", line 4292, in setup_entity
    self._with_polymorphic = ext_info.with_polymorphic_mappers

  File "E:\Programs\anaconda3\lib\site-packages\sqlalchemy\util\langhelpers.py", line 883, in __get__
    obj.__dict__[self.__name__] = result = self.fget(obj)

  File "E:\Programs\anaconda3\lib\site-packages\sqlalchemy\orm\mapper.py", line 2158, in _with_polymorphic_mappers
    configure_mappers()

  File "E:\Programs\anaconda3\lib\site-packages\sqlalchemy\orm\mapper.py", line 3276, in configure_mappers
    raise e

System Information:

  • OS: Windows 10
  • Anaconda 3
  • Spyder 4.1.4

Branch:

  • master

Additional info
I am not sure which tables are involved, am I missing something?
testbot.txt

Faulty creation of client_id

Describe the bug
A clear and concise description of what the bug is.
I have bee using pyjuque in test mode and also in live mode. I see the bot getting a signal and trying to place the order. While doing so I get like the same kind of error on both of my exchanges. I use bitpanda and kraken.
for Bitpanda the error is
{"error":"INVALID_CLIENT_UUID"}

for Kranken I get this
<class 'ccxt.base.errors.ExchangeError'>
kraken {"error":["EGeneral:Invalid arguments:userref"]}

I am new to python programming so I am not quite sure. I was going through the code and I always get to a point where the custom_order_id is being involved.

Expected behavior
calling ccxt.createorder directly leads to an order being palced on the exchange without error.

Desktop (please complete the following information):

  • OS: windows 10
    using pycharm21.1 and python 3.8.5

In the code I saw that for the uuid4 the dashes were replaced/removed. So maybe thats the reason for the uuid being faulty.

Thanks
Jochen

Interest in using Pandas TA as a TA Library?

Hello @tudorelu,

I came across your Github account through another user and saw that you are creating an Algo Trading System and posting via YouTube. Awesome!

I noticed that you are using pyti for TA but it seems to have gone stale nearly two years ago. I was wondering if you would be interested in trying and incorporating Pandas TA into your project? It is built to be compatible with Pandas as an DataFrame extension, correlated with TA Lib (for common indicators), other popular indicators like TTM Squeeze and Trend, and much more! Also check out some Examples for implementation and features.

Thanks for your time,
Kevin Johnson

Error executing examples/try_order_management.py in feature branch / order_management

Description
When i am execute the python file examples/try_order_management.py in feature/order_management,
i will get following error stack:

$ python examples/try_order_management.py 
Getting active pairs:
Traceback (most recent call last):
  File "examples/try_order_management.py", line 73, in <module>
    Main()
  File "examples/try_order_management.py", line 63, in Main
    execute_bot(
  File "E:\Develop\pyjuque\bot\Engine\OrderManagement.py", line 16, in execute_bot
    active_pairs = bot.getActivePairs(session)
AttributeError: 'NoneType' object has no attribute 'getActivePairs'

System Information

  • Windows 10 Professional
  • VS Code V1.48.1
  • Python 3.8.2

Additional Info
I think some values are not set in the database at this point, so it deliver a NoneType Error. I hope you can help me at this point to figure what the problem is in this case.

Thank you very much!

i have the bot running in pycharm, but its not placing order on binance us order book. ive watched your recent tuts and seen that this bot can go on multpy exchanges.

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

okex exchange didn't work

okex exchange now didn't work - api change from api-v3 to api-v5
pip install ccxt==1.56.29 --no-deps
fix this problem

Grid Bot - Margin

I see that you are working on a grid bot. I've been looking for weeks for a grid that can work with Margin like the ones at Pionex do. That would be a killer feature that I'd be happy to compensate for!

Bot does not stop with Ctrl+C?

Hello,

I have the typical loop in my file:

def main():
	bot_controller = defineBot(bot_config)

	while True:
		try:
			bot_controller.executeBot()
		except KeyboardInterrupt:
			return

		sleep(15)

However, when I hit ctrl+c the terminal appears to react but not actually stop the program:
image

Am I misunderstanding something?

Thanks

NULL value in match_order_id

I noticed the bot forgot to update match_order_id in the order table. I'm trying to figure out how to add some maintenance function in the bot to let it populate the match_order_id from current_order_id from pair table when it detects the match_order_id is blank...

Once in a while, the stop loss is putting a the buy match_order_id in sell match_order_id during cancel sell but the bot didn't notice it forgot to submit the order, which caused the match_order_id different from the order.id.

I was able to copy and paste the id into match_order_id manually to get the bot to stop screaming about orders not found. There's a lot of manual update on the database by hand because I can't seem to find the codes to fix the bott so it won't have mismatch id or NULL id.

How to

can you please help me to get your project working......I love the concept and want to use this to trade but cant get it to start up

C:\Users\mayhe\OneDrive\Desktop\pyjuque-master\pyjuque-master\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1.1\plugins\python-ce\helpers\pydev\pydevd.py" --multiproc --qt-support=auto --client 127.0.0.1 --port 53101 --file C:/Users/mayhe/OneDrive/Desktop/pyjuque-master/pyjuque-master/main.py
Connected to pydev debugger (build 211.7142.13)
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1.1\plugins\python-ce\helpers\pydev\pydevd.py", line 1483, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1.1\plugins\python-ce\helpers\pydev_pydev_imps_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/mayhe/OneDrive/Desktop/pyjuque-master/pyjuque-master/main.py", line 17
'exchange' :
^
SyntaxError: invalid syntax

Process finished with exit code 1
Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Balance & Selling manually caused pyjuque notification messages non-stop

Describe the bug

I added more funds in the exchange but pyjuque didn't notice because it's still using the starting/current balance from the database instead letting me update the balance:
INFO:pyjuque.Engine.BotController:Error placing order
<class 'ccxt.base.errors.InsufficientFunds'>

I manually sold the coin on the market. But pyjuque didn't notice it and kept on trying to access the record in the database and notify about it. Is there any to get rid of the old/expired records in the database?
INFO:pyjuque.Engine.BotController:Error getting data from the exchange for updating open order

Symbol in DB but not bot_config

Hi Tudor,

I noticed that even though my bot_config has 'symbols': ['BTC/USDT', 'ETH/USDT'], in the DB table called pair 3 symbols show up (BTC, ETH and ADA) and ADA appears as active. Also ADA appears in the terminal when I executeBot().

Is the bot respecting my bot_config?

Thank you!

Cannot trade symbol without '/' in the name

FTX has futures. They have symbols like ETH-PERP.

If I try to load up this symbol I get the error:

  File ".../lib/python3.9/site-packages/pyjuque/Bot.py", line 65, in defineBot
    quote_asset = symbols[0].split('/')[1]
IndexError: list index out of range

Screenshot 2021-08-22 at 12 09 12

InsufficientFunds error placing Sell order despite enough Binance balance

Describe the bug
Even though my Binance balance is 1000 EUR, InsufficientFunds error is raised when bot_config has starting_balance = 500 and initial_entry_allocation = 20. However, when I try with starting_balance = 100 and initial_entry_allocation = 20 no error appears.

It is important to mention that the error shows up when the bot is trying to place the Sell order.

To Reproduce
Set bot_config to the following, ensure you have more than 500 EUR in your Binance balance. Then run defineBot() and executeBot().

bot_config = {
	'name': 'bot0',
        'test_run': False,
	'exchange': exchange_binance,
	'symbols': ['BTC/EUR', 'ETH/EUR', 'ADA/EUR'],
	'starting_balance': 500.00,
	'strategy': {
		'class': BBRSIStrategy,
		'params': {
			'bb_len': 20,
			'n_std': 2.0,
			'rsi_len': 14,
			'rsi_overbought': 60,
			'rsi_oversold': 40,
		}
	},
	'timeframe': '5m',
	'entry_settings': {
		'initial_entry_allocation': 20,
		'signal_distance': 0.1
	},
	'exit_settings': {
		'take_profit': 2,
		'stop_loss_value': 1
	},
	'display_status': True
}

Expected behavior
InsufficientFunds error should not be raised when the Binance balance is greater than the starting_balance.

Screenshots
image

Desktop (please complete the following information):

  • OS: Windows 10
  • Browser: N/A
  • Version: pyjuque 0.1.1.9

Additional context
Typically it happens placing the second Sell order, but occasionally it happened during the first Sell order.

open_buy_order_time_out

How to use the the open buy order time out?
i dont know how to use this parameter......or whats the time format to use this option

Get Bot Started

I cant seem to get this bot to work, can i get some beginner instructions on this matter

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.