├── requirements.txt ├── test-requirements.txt ├── MANIFEST.in ├── .gitignore ├── README.md ├── pybitmex ├── __init__.py ├── models.py ├── auth.py ├── rest.py ├── ws.py └── bitmex.py ├── setup.py ├── sample.py └── LICENSE /requirements.txt: -------------------------------------------------------------------------------- 1 | websocket-client>=0.56.0 2 | requests>=2.21.0 3 | python-dateutil>=2.8.0 4 | -------------------------------------------------------------------------------- /test-requirements.txt: -------------------------------------------------------------------------------- 1 | websocket-client>=0.56.0 2 | requests>=2.21.0 3 | python-dateutil>=2.8.0 4 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include *.md 3 | exclude README.md 4 | include requirements.txt 5 | include test-requirements.txt 6 | exclude sample.py 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /settings.py 2 | /*settings.py 3 | 4 | venv/ 5 | 6 | build/ 7 | dist/ 8 | *.egg-info/ 9 | 10 | .idea/ 11 | .pytest_cache 12 | .coverage 13 | *.pyc 14 | 15 | *.log 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pybitmex 2 | 3 | WebSocket and REST client library 4 | for [BitMEX API](https://www.bitmex.com/app/apiOverview) written in Python. 5 | 6 | [![GPL-3.0](https://img.shields.io/github/license/yanagisawa-kentaro-777/bitmex_watcher.svg)](LICENSE) 7 | [![PyPI version](https://badge.fury.io/py/pybitmex.svg)](https://badge.fury.io/py/pybitmex) 8 | 9 | ## Requirements 10 | Python 3.6+ -------------------------------------------------------------------------------- /pybitmex/__init__.py: -------------------------------------------------------------------------------- 1 | from .bitmex import BitMEXClient 2 | from .models import Trade, OpenOrder, OpenOrders 3 | from .rest import RestClientError 4 | 5 | __copyright__ = 'Copyright (C) 2019 Weidenthal Research Institute LLC' 6 | __version__ = '0.5.5' 7 | __license__ = 'GNU General Public License v3 (GPLv3)' 8 | __author__ = 'YANAGISAWA, Kentaro' 9 | __author_email__ = 'yanagisawa.kentaro@weidenthal.co.jp' 10 | __url__ = 'https://github.com/yanagisawa-kentaro-777/pybitmex' 11 | 12 | __all__ = ["BitMEXClient", "Trade", "OpenOrder", "OpenOrders", "RestClientError"] 13 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | from codecs import open 3 | from os import path 4 | import re 5 | 6 | package_name = "pybitmex" 7 | 8 | root_dir = path.abspath(path.dirname(__file__)) 9 | 10 | 11 | def _requirements(): 12 | return [name.rstrip() for name in open(path.join(root_dir, 'requirements.txt')).readlines()] 13 | 14 | 15 | def _test_requirements(): 16 | return [name.rstrip() for name in open(path.join(root_dir, 'test-requirements.txt')).readlines()] 17 | 18 | 19 | with open(path.join(root_dir, package_name, '__init__.py')) as f: 20 | init_text = f.read() 21 | version = re.search(r'__version__\s*=\s*[\'\"](.+?)[\'\"]', init_text).group(1) 22 | license = re.search(r'__license__\s*=\s*[\'\"](.+?)[\'\"]', init_text).group(1) 23 | author = re.search(r'__author__\s*=\s*[\'\"](.+?)[\'\"]', init_text).group(1) 24 | author_email = re.search(r'__author_email__\s*=\s*[\'\"](.+?)[\'\"]', init_text).group(1) 25 | url = re.search(r'__url__\s*=\s*[\'\"](.+?)[\'\"]', init_text).group(1) 26 | 27 | assert version 28 | assert license 29 | assert author 30 | assert author_email 31 | assert url 32 | 33 | long_description = 'Websocket and REST client library for BitMEX.' 34 | 35 | 36 | setup( 37 | name=package_name, 38 | packages=[package_name], 39 | 40 | version=version, 41 | 42 | license=license, 43 | 44 | install_requires=_requirements(), 45 | tests_require=_test_requirements(), 46 | 47 | author=author, 48 | author_email=author_email, 49 | 50 | url=url, 51 | 52 | description='Websocket and REST client library for BitMEX.', 53 | long_description=long_description, 54 | keywords='BitMEX, trading, trade, cryptocurrency', 55 | 56 | classifiers=[ 57 | 'Development Status :: 4 - Beta', 58 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 59 | 'Programming Language :: Python', 60 | 'Programming Language :: Python :: 3.6', 61 | 'Topic :: Office/Business :: Financial', 62 | 'Topic :: Software Development :: Libraries :: Python Modules', 63 | ], 64 | ) 65 | -------------------------------------------------------------------------------- /pybitmex/models.py: -------------------------------------------------------------------------------- 1 | 2 | class Trade: 3 | 4 | def __init__(self, _trd_match_id, _timestamp, _side, _price, _size): 5 | self.trd_match_id = _trd_match_id 6 | self.timestamp = _timestamp 7 | self.side = _side 8 | self.price = _price 9 | self.size = _size 10 | # Redundant fields for the convenience of aggregation. 11 | if self.side == "Buy": 12 | bought_size = self.size 13 | sold_size = 0 14 | else: 15 | sold_size = self.size 16 | bought_size = 0 17 | self.momentum = bought_size - sold_size 18 | 19 | def __str__(self): 20 | return str(self.to_dict()) 21 | 22 | def to_dict(self): 23 | return { 24 | 'trdMatchID': self.trd_match_id, 25 | 'timestamp': self.timestamp, 26 | 'side': self.side, 27 | 'price': self.price, 28 | 'size': self.size, 29 | "momentum": self.momentum 30 | } 31 | 32 | 33 | class OpenOrder: 34 | 35 | def __init__(self, order_id, client_order_id, side, quantity, price, timestamp): 36 | self.order_id = order_id 37 | self.client_order_id = client_order_id 38 | self.side = side 39 | self.quantity = quantity 40 | self.price = price 41 | self.timestamp = timestamp 42 | 43 | def __str__(self): 44 | return "Side: {}; Quantity: {:d}; Price: {:.1f}; OrderID: {}; ClOrdID: {}; Timestamp: {}; ".format( 45 | self.side, self.quantity, self.price, self.order_id, self.client_order_id, 46 | self.timestamp.strftime("%Y%m%d_%H%M%S") 47 | ) 48 | 49 | 50 | class OpenOrders: 51 | 52 | def __init__(self, bids, asks): 53 | self.bids = bids 54 | self.asks = asks 55 | 56 | def remove_orders(self, remove_targets): 57 | new_bids = [b for b in self.bids if b.order_id not in remove_targets] 58 | new_asks = [a for a in self.asks if a.order_id not in remove_targets] 59 | return OpenOrders(bids=new_bids, asks=new_asks) 60 | 61 | def to_list(self): 62 | return self.bids + self.asks 63 | -------------------------------------------------------------------------------- /sample.py: -------------------------------------------------------------------------------- 1 | import time 2 | from pybitmex import * 3 | from datetime import datetime, timedelta, timezone 4 | 5 | bitmex = BitMEXClient( 6 | "https://www.bitmex.com/api/v1/", "XBTUSD", 7 | api_key=None, api_secret=None, 8 | use_websocket=True, use_rest=True, 9 | subscriptions=["instrument", "orderBookL2", "trade", "margin", "order", "position"] 10 | ) 11 | while True: 12 | time.sleep(3) 13 | started = datetime.now() 14 | 15 | state = bitmex.ws_market_state() 16 | print("Market: {}".format(state)) 17 | 18 | bids, asks = bitmex.ws_sorted_bids_and_asks_of_market() 19 | print("{:.1f} & {:.1f} ({:,d} bids and {:,d} asks)".format( 20 | bids[0]["price"], asks[0]["price"], len(bids), len(asks) 21 | )) 22 | print("Boards: {:.2f} seconds".format((datetime.now() - started).total_seconds())) 23 | last_update = bitmex.get_last_ws_update("orderBookL2") 24 | print("Last update of boards: {}".format(str(last_update))) 25 | 26 | trades = bitmex.ws_sorted_recent_trade_objects_of_market() 27 | print("{:,d} recent trades".format(len(trades))) 28 | print("Last update of trades: {}".format(str(bitmex.get_last_ws_update("trade")))) 29 | 30 | open_orders = bitmex.ws_open_order_objects_of_account() 31 | print("{:d} open bids and {:d} open asks".format(len(open_orders.bids), len(open_orders.asks))) 32 | 33 | position_size = bitmex.ws_current_position_size() 34 | print("position: {:,d}".format(position_size)) 35 | 36 | withdrawble_balance, wallet_balance = bitmex.ws_balances_of_account_object() 37 | print("Balance: {:.8f} / {:.8f}".format(withdrawble_balance, wallet_balance)) 38 | 39 | end = datetime.now() 40 | print("Total: {:.2f} seconds".format((end - started).total_seconds())) 41 | print("") 42 | 43 | #rest_open_orders = bitmex.rest_get_raw_orders_of_account({"open": True}) 44 | #print("REST Open Orders: {}".format(str(rest_open_orders))) 45 | 46 | # filter_obj = bitmex.create_hourly_filter(2019, 4, 14, 1) 47 | filter_obj = bitmex.create_time_range_filter(datetime.now().astimezone(timezone.utc) - 48 | timedelta(hours=2), datetime.now().astimezone(timezone.utc)) 49 | print(str(filter_obj)) 50 | rest_trade_history =\ 51 | bitmex.rest_get_raw_trade_history_of_account(filter_obj, count=500) 52 | print(len(rest_trade_history)) 53 | print(str(rest_trade_history[0]['timestamp']) + " " + (rest_trade_history[-1]['timestamp'])) 54 | #print("") 55 | 56 | -------------------------------------------------------------------------------- /pybitmex/auth.py: -------------------------------------------------------------------------------- 1 | import time 2 | import urllib 3 | import hmac 4 | import hashlib 5 | 6 | from requests.auth import AuthBase 7 | 8 | 9 | def expiration_time(expiration_seconds): 10 | return int(round(time.time() + expiration_seconds)) 11 | 12 | 13 | # Generates an API signature. 14 | # A signature is HMAC_SHA256(secret, verb + path + nonce + data), hex encoded. 15 | # Verb must be uppercased, url is relative, nonce must be an increasing 64-bit integer 16 | # and the data, if present, must be JSON without whitespace between keys. 17 | # 18 | # For example, in psuedocode (and in real code below): 19 | # 20 | # verb=POST 21 | # url=/api/v1/order 22 | # nonce=1416993995705 23 | # data={"symbol":"XBTZ14","quantity":1,"price":395.01} 24 | # signature = HEX(HMAC_SHA256(secret, 'POST/api/v1/order1416993995705{"symbol":"XBTZ14","quantity":1,"price":395.01}')) 25 | def generate_signature(secret, verb, url, nonce, data): 26 | """Generate a request signature compatible with BitMEX.""" 27 | # Parse the url so we can remove the base and extract just the path. 28 | parsed_uri = urllib.parse.urlparse(url) 29 | path = parsed_uri.path 30 | if parsed_uri.query: 31 | path = path + '?' + parsed_uri.query 32 | 33 | if isinstance(data, (bytes, bytearray)): 34 | data = data.decode('utf8') 35 | message = (verb + path + str(nonce) + data).encode('utf-8') 36 | 37 | signature = hmac.new(secret.encode('utf-8'), message, digestmod=hashlib.sha256).hexdigest() 38 | return signature 39 | 40 | 41 | class APIKeyAuthWithExpires(AuthBase): 42 | 43 | """Attaches API Key Authentication to the given Request object. This implementation uses `expires`.""" 44 | 45 | def __init__(self, key, secret, expiration_seconds): 46 | """Init with Key & Secret.""" 47 | self.api_key = key 48 | self.api_secret = secret 49 | self.expiration_seconds = expiration_seconds 50 | 51 | def __call__(self, r): 52 | """ 53 | Called when forming a request - generates api key headers. This call uses `expires` instead of nonce. 54 | 55 | This way it will not collide with other processes using the same API Key if requests arrive out of order. 56 | For more details, see https://www.bitmex.com/app/apiKeys 57 | """ 58 | # modify and return the request 59 | expires = expiration_time(self.expiration_seconds) 60 | r.headers['api-expires'] = str(expires) 61 | r.headers['api-key'] = self.api_key 62 | r.headers['api-signature'] = generate_signature(self.api_secret, r.method, r.url, expires, r.body or '') 63 | 64 | return r 65 | -------------------------------------------------------------------------------- /pybitmex/rest.py: -------------------------------------------------------------------------------- 1 | import time 2 | import json 3 | 4 | import logging 5 | 6 | import base64 7 | import uuid 8 | 9 | import requests 10 | 11 | from pybitmex.auth import APIKeyAuthWithExpires 12 | 13 | 14 | class RestClientError(Exception): 15 | def __init__(self, message_str, error_code): 16 | self.message_str = message_str 17 | self.error_code = error_code 18 | super(RestClientError, self).__init__(message_str) 19 | 20 | def is_unknown(self): 21 | return self.error_code < 0 22 | 23 | def is_timeout(self): 24 | return 999 <= self.error_code 25 | 26 | def is_4xx(self): 27 | return 400 <= self.error_code < 500 28 | 29 | def is_5xx(self): 30 | return 500 <= self.error_code < 600 31 | 32 | 33 | class RestClient: 34 | 35 | def __init__( 36 | self, uri, api_key=None, api_secret=None, 37 | symbol="XBTUSD", 38 | order_id_prefix="", 39 | agent_name="trading_bot", 40 | timeout=7, 41 | expiration_seconds=3600 42 | ): 43 | self.logger = logging.getLogger(__name__) 44 | 45 | self.base_url = uri 46 | self.api_key = api_key 47 | self.api_secret = api_secret 48 | 49 | self.symbol = symbol 50 | self.order_id_prefix = order_id_prefix 51 | 52 | # Prepare HTTPS session 53 | self.session = requests.Session() 54 | # These headers are always sent 55 | self.session.headers.update({'user-agent': agent_name}) 56 | self.session.headers.update({'content-type': 'application/json'}) 57 | self.session.headers.update({'accept': 'application/json'}) 58 | 59 | self.timeout = timeout 60 | self.expiration_seconds = expiration_seconds 61 | self.retries = 0 62 | 63 | def close(self): 64 | self.session.close() 65 | 66 | def curl_bitmex(self, path, query=None, postdict=None, timeout=None, verb=None, max_retries=None): 67 | """Send a request to BitMEX Servers.""" 68 | # Handle URL 69 | uri = self.base_url + path 70 | 71 | if timeout is None: 72 | timeout = self.timeout 73 | 74 | # Default to POST if data is attached, GET otherwise 75 | if not verb: 76 | verb = 'POST' if postdict else 'GET' 77 | 78 | # By default don't retry POST or PUT. Retrying GET/DELETE is okay because they are idempotent. 79 | # In the future we could allow retrying PUT, so long as 'leavesQty' is not used (not idempotent), 80 | # or you could change the clOrdID (set {"clOrdID": "new", "origClOrdID": "old"}) so that an amend 81 | # can't erroneously be applied twice. 82 | if max_retries is None: 83 | max_retries = 0 if verb in ['POST', 'PUT'] else 3 84 | 85 | # Auth: API Key/Secret 86 | auth = APIKeyAuthWithExpires(self.api_key, self.api_secret, self.expiration_seconds) 87 | 88 | def rethrow(message_str, code): 89 | raise RestClientError(message_str, code) 90 | 91 | def retry(sleep_seconds, code): 92 | self.retries += 1 93 | if max_retries < self.retries: 94 | rethrow("Max retries on {} {} hit.".format(verb, uri), code) 95 | 96 | if 0 <= sleep_seconds: 97 | seconds_to_sleep = sleep_seconds 98 | else: 99 | seconds_to_sleep = self.retries 100 | time.sleep(seconds_to_sleep) 101 | return self.curl_bitmex(path, query, postdict, timeout, verb, max_retries) 102 | 103 | # Make the request 104 | response = None 105 | try: 106 | self.logger.info("Requesting %s to %s", verb, uri) 107 | req = requests.Request(verb, uri, json=postdict, auth=auth, params=query) 108 | prepped = self.session.prepare_request(req) 109 | response = self.session.send(prepped, timeout=timeout) 110 | # Make non-200s throw 111 | response.raise_for_status() 112 | 113 | # Reset retry counter on success 114 | self.retries = 0 115 | return response.json() 116 | except requests.exceptions.HTTPError as e: 117 | if response is None: 118 | rethrow("Unknown Error", -1) 119 | 120 | # 401 - Auth error. This is fatal. 121 | if response.status_code == 401: 122 | # Always exit, even if rethrow_errors, because this is fatal 123 | rethrow(json.dumps(response.json()), response.status_code) 124 | # 404, can be thrown if order canceled or does not exist. 125 | elif response.status_code == 404: 126 | if verb == 'DELETE': 127 | return 128 | rethrow(json.dumps(response.json()), response.status_code) 129 | # 429, rate limit; cancel orders & wait until X-RateLimit-Reset 130 | elif response.status_code == 429: 131 | # Figure out how long we need to wait. 132 | rate_limit_reset = response.headers['X-RateLimit-Reset'] 133 | to_sleep = int(rate_limit_reset) - int(time.time()) 134 | self.logger.warning("Rate limited. Sleeping %d seconds.", to_sleep) 135 | time.sleep(to_sleep) 136 | 137 | # Retry the request. 138 | return retry(0, response.status_code) 139 | # 503 - BitMEX temporary downtime, likely due to a deploy. Try again 140 | elif response.status_code == 503: 141 | error = response.json()['error'] 142 | message = error['message'].lower() if error else '' 143 | self.logger.info(message) 144 | return retry(-1, response.status_code) 145 | elif response.status_code == 400: 146 | error = response.json()['error'] 147 | message = error['message'].lower() if error else '' 148 | self.logger.warning(message) 149 | rethrow(json.dumps(response.json()), response.status_code) 150 | # If we haven't returned or re-raised yet, we get here. 151 | rethrow(json.dumps(response.json()), response.status_code) 152 | except requests.exceptions.Timeout as e: 153 | # Timeout, re-run this request 154 | self.logger.info("Request timed out: %s %s", verb, uri) 155 | return retry(0, 999) 156 | except requests.exceptions.ConnectionError as e: 157 | self.logger.warning("Connection error.") 158 | return retry(3, 999) 159 | 160 | def get_trade_history(self, filter_json_obj, count=500): 161 | path = 'execution/tradeHistory?count={:d}'.format(count) +\ 162 | '&filter=' + json.dumps(filter_json_obj) 163 | return self.curl_bitmex(path=path, verb='GET') 164 | 165 | def get_orders_of_account(self, filter_json_obj, count=500): 166 | path = 'order?count={:d}'.format(count) +\ 167 | '&filter=' + json.dumps(filter_json_obj) 168 | return self.curl_bitmex(path=path, verb='GET') 169 | 170 | def get_positions_of_account(self, filter_json_obj, count=500): 171 | path = 'position?count={:d}'.format(count) +\ 172 | '&filter=' + json.dumps(filter_json_obj) 173 | return self.curl_bitmex(path=path, verb='GET') 174 | 175 | def get_user_margin(self): 176 | path = 'user/margin' 177 | return self.curl_bitmex(path=path, verb='GET') 178 | 179 | def place_orders(self, orders, post_only=True, max_retries=None): 180 | """Create multiple orders.""" 181 | for order in orders: 182 | if order.get('clOrdID') is None: 183 | order['clOrdID'] = self.order_id_prefix +\ 184 | base64.b64encode(uuid.uuid4().bytes).decode('utf8').rstrip('=\n') 185 | order['symbol'] = self.symbol 186 | if post_only: 187 | order['execInst'] = 'ParticipateDoNotInitiate' 188 | return self.curl_bitmex(path='order/bulk', postdict={'orders': orders}, verb='POST', max_retries=max_retries) 189 | 190 | def market_close_position(self, order, max_retries=None): 191 | if order.get('clOrdID') is None: 192 | order['clOrdID'] = self.order_id_prefix + \ 193 | base64.b64encode(uuid.uuid4().bytes).decode('utf8').rstrip('=\n') 194 | order['symbol'] = self.symbol 195 | order['ordType'] = 'Market' 196 | order['execInst'] = 'Close' 197 | return self.curl_bitmex(path='order', postdict=order, verb='POST', max_retries=max_retries) 198 | 199 | def cancel_orders(self, order_id_list, max_retries=None): 200 | """Cancel an existing order.""" 201 | path = "order" 202 | postdict = { 203 | 'orderID': order_id_list, 204 | } 205 | return self.curl_bitmex(path=path, postdict=postdict, verb="DELETE", max_retries=max_retries) 206 | -------------------------------------------------------------------------------- /pybitmex/ws.py: -------------------------------------------------------------------------------- 1 | import math 2 | import threading 3 | import traceback 4 | 5 | from time import sleep 6 | import json 7 | import logging 8 | import urllib 9 | 10 | import websocket 11 | 12 | from pybitmex.auth import expiration_time, generate_signature 13 | 14 | 15 | # Naive implementation of connecting to BitMEX websocket for streaming real time data. 16 | # The traders still interacts with this as if it were a REST Endpoint, but now it can get 17 | # much more real time data without polling the hell out of the API. 18 | # 19 | # The WebSocket offers a bunch of data as raw properties right on the object. 20 | # On connect, it synchronously asks for a push of all this data then returns. 21 | # Right after, the MM can start using its data. It will be updated in real time, so the MM can 22 | # poll really often if it wants. 23 | class BitMEXWebSocketClient: 24 | 25 | # Don't grow a table larger than this amount. Helps cap memory usage. 26 | MAX_TABLE_LEN = 200 27 | 28 | def __init__(self, endpoint, symbol, api_key=None, api_secret=None, subscriptions=None, expiration_seconds=3600): 29 | '''Connect to the websocket and initialize data stores.''' 30 | self.logger = logging.getLogger(__name__) 31 | self.logger.debug("Initializing WebSocket.") 32 | 33 | self.endpoint = endpoint 34 | self.symbol = symbol 35 | 36 | self.expiration_seconds = expiration_seconds 37 | 38 | if api_key is not None and api_secret is None: 39 | raise ValueError('api_secret is required if api_key is provided') 40 | if api_key is None and api_secret is not None: 41 | raise ValueError('api_key is required if api_secret is provided') 42 | 43 | self.api_key = api_key 44 | self.api_secret = api_secret 45 | 46 | if subscriptions is not None: 47 | self.subscription_list = subscriptions 48 | else: 49 | self.subscription_list =\ 50 | ["execution", "instrument", "margin", "order", "orderBookL2", "position", "quote", "trade"] 51 | 52 | self.updates = {} 53 | self.data = {} 54 | self.keys = {} 55 | self.exited = False 56 | 57 | # We can subscribe right in the connection querystring, so let's build that. 58 | # Subscribe to all pertinent endpoints 59 | ws_uri = self.__get_url() 60 | self.logger.info("Connecting to %s" % ws_uri) 61 | self.__connect(ws_uri, symbol) 62 | self.logger.info('Connected to WS.') 63 | 64 | # Connected. Wait for partials 65 | self.__wait_for_data_arrival(symbol) 66 | self.logger.info('Got all market data. Starting.') 67 | 68 | @staticmethod 69 | def _now(): 70 | from datetime import datetime, timezone 71 | return datetime.now().astimezone(timezone.utc) 72 | 73 | def exit(self): 74 | '''Call this to exit - will close websocket.''' 75 | self.exited = True 76 | self.ws.close() 77 | 78 | def get_instrument(self): 79 | '''Get the raw instrument data for this symbol.''' 80 | # Turn the 'tickSize' into 'tickLog' for use in rounding 81 | instrument = self.data['instrument'][0] 82 | instrument['tickLog'] = int(math.fabs(math.log10(instrument['tickSize']))) 83 | return instrument 84 | 85 | def get_ticker(self): 86 | '''Return a ticker object. Generated from quote and trade.''' 87 | last_quote = self.data['quote'][-1] 88 | last_trade = self.data['trade'][-1] 89 | ticker = { 90 | "last": last_trade['price'], 91 | "buy": last_quote['bidPrice'], 92 | "sell": last_quote['askPrice'], 93 | "mid": (float(last_quote['bidPrice'] or 0) + float(last_quote['askPrice'] or 0)) / 2 94 | } 95 | 96 | # The instrument has a tickSize. Use it to round values. 97 | instrument = self.data['instrument'][0] 98 | if 'tickLog' in instrument: 99 | return {k: round(float(v or 0), instrument['tickLog']) for k, v in ticker.items()} 100 | else: 101 | return {} 102 | 103 | def funds(self): 104 | '''Get your margin details.''' 105 | return self.data['margin'][0] 106 | 107 | def positions(self): 108 | '''Get your positions.''' 109 | return self.data['position'] 110 | 111 | def executions(self): 112 | return self.data['execution'] 113 | 114 | def get_order_book_table_name(self): 115 | if 'orderBookL2' in self.data: 116 | return 'orderBookL2' 117 | elif 'orderBookL2_25' in self.data: 118 | return 'orderBookL2_25' 119 | else: 120 | return 'orderBook10' 121 | 122 | def market_depth(self): 123 | '''Get market depth (orderbook). Returns all levels.''' 124 | table_name = self.get_order_book_table_name() 125 | return self.data[table_name] 126 | 127 | def open_orders(self, clOrdIDPrefix): 128 | '''Get all your open orders.''' 129 | orders = self.data['order'] 130 | # Filter to only open orders and those that we actually placed 131 | return [o for o in orders if str(o['clOrdID']).startswith(clOrdIDPrefix) and order_leaves_quantity(o)] 132 | 133 | def recent_trades(self): 134 | '''Get recent trades.''' 135 | return self.data['trade'] 136 | 137 | # 138 | # End Public Methods 139 | # 140 | 141 | def __connect(self, wsURL, symbol): 142 | '''Connect to the websocket in a thread.''' 143 | self.logger.debug("Starting thread") 144 | 145 | self.ws = websocket.WebSocketApp(wsURL, 146 | on_message=self.__on_message, 147 | on_close=self.__on_close, 148 | on_open=self.__on_open, 149 | on_error=self.__on_error, 150 | header=self.__get_auth()) 151 | 152 | self.wst = threading.Thread(target=lambda: self.ws.run_forever()) 153 | self.wst.daemon = True 154 | self.wst.start() 155 | self.logger.debug("Started thread") 156 | 157 | # Wait for connect before continuing 158 | conn_timeout = 5 159 | while not self.ws.sock or not self.ws.sock.connected and conn_timeout: 160 | sleep(1) 161 | conn_timeout -= 1 162 | if not conn_timeout: 163 | self.logger.error("Couldn't connect to WS! Exiting.") 164 | self.exit() 165 | raise websocket.WebSocketTimeoutException('Couldn\'t connect to WS! Exiting.') 166 | 167 | def __get_auth(self): 168 | '''Return auth headers. Will use API Keys if present in settings.''' 169 | if self.api_key: 170 | self.logger.info("Authenticating with API Key.") 171 | # To auth to the WS using an API key, we generate a signature of a nonce and 172 | # the WS API endpoint. 173 | expires = expiration_time(self.expiration_seconds) 174 | return [ 175 | "api-expires: " + str(expires), 176 | "api-signature: " + generate_signature(self.api_secret, 'GET', '/realtime', expires, ''), 177 | "api-key:" + self.api_key 178 | ] 179 | else: 180 | self.logger.info("Not authenticating.") 181 | return [] 182 | 183 | def __get_url(self): 184 | import copy 185 | 186 | ''' 187 | Generate a connection URL. We can define subscriptions right in the querystring. 188 | Most subscription topics are scoped by the symbol we're listening to. 189 | ''' 190 | 191 | # You can sub to orderBookL2 for all levels, or orderBook10 for top 10 levels & save bandwidth 192 | subscriptions_per_symbol = copy.copy(self.subscription_list) 193 | if "margin" in subscriptions_per_symbol: 194 | subscriptions_per_symbol.remove("margin") 195 | generic_subscriptions = ["margin"] 196 | else: 197 | generic_subscriptions = [] 198 | 199 | subscriptions = [sub + ':' + self.symbol for sub in subscriptions_per_symbol] 200 | subscriptions += generic_subscriptions 201 | 202 | uri_parts = list(urllib.parse.urlparse(self.endpoint)) 203 | uri_parts[0] = uri_parts[0].replace('http', 'ws') 204 | uri_parts[2] = "/realtime?subscribe={}".format(','.join(subscriptions)) 205 | 206 | return urllib.parse.urlunparse(uri_parts) 207 | 208 | def __wait_for_data_arrival(self, symbol): 209 | '''On subscribe, this data will come down. Wait for it.''' 210 | targets = set(self.subscription_list) 211 | while not targets <= set(self.data): 212 | sleep(0.1) 213 | 214 | def __send_command(self, command, args=None): 215 | '''Send a raw command.''' 216 | if args is None: 217 | args = [] 218 | self.ws.send(json.dumps({"op": command, "args": args})) 219 | 220 | def __on_message(self, message): 221 | '''Handler for parsing WS messages.''' 222 | message = json.loads(message) 223 | self.logger.debug(json.dumps(message)) 224 | 225 | table = message.get('table') 226 | action = message.get('action') 227 | # Remember the time of update. 228 | if table is not None and 0 < len(table): 229 | self.updates[table] = self._now() 230 | try: 231 | if 'subscribe' in message: 232 | self.logger.debug("Subscribed to %s." % message['subscribe']) 233 | elif action: 234 | 235 | if table not in self.data: 236 | self.data[table] = [] 237 | 238 | # There are four possible actions from the WS: 239 | # 'partial' - full table image 240 | # 'insert' - new row 241 | # 'update' - update row 242 | # 'delete' - delete row 243 | if action == 'partial': 244 | self.logger.debug("%s: partial" % table) 245 | self.data[table] += message['data'] 246 | # Keys are communicated on partials to let you know how to uniquely identify 247 | # an item. We use it for updates. 248 | self.keys[table] = message['keys'] 249 | elif action == 'insert': 250 | self.logger.debug('%s: inserting %s' % (table, message['data'])) 251 | self.data[table] += message['data'] 252 | 253 | # Limit the max length of the table to avoid excessive memory usage. 254 | # Don't trim orders because we'll lose valuable state if we do. 255 | if table not in ['order', 'orderBookL2'] and len(self.data[table]) > BitMEXWebSocketClient.MAX_TABLE_LEN: 256 | self.data[table] = self.data[table][BitMEXWebSocketClient.MAX_TABLE_LEN // 2:] 257 | 258 | elif action == 'update': 259 | self.logger.debug('%s: updating %s' % (table, message['data'])) 260 | # Locate the item in the collection and update it. 261 | for updateData in message['data']: 262 | item = find_by_keys(self.keys[table], self.data[table], updateData) 263 | if not item: 264 | return # No item found to update. Could happen before push 265 | item.update(updateData) 266 | # Remove cancelled / filled orders 267 | if table == 'order' and not order_leaves_quantity(item): 268 | self.data[table].remove(item) 269 | elif action == 'delete': 270 | self.logger.debug('%s: deleting %s' % (table, message['data'])) 271 | # Locate the item in the collection and remove it. 272 | for deleteData in message['data']: 273 | item = find_by_keys(self.keys[table], self.data[table], deleteData) 274 | self.data[table].remove(item) 275 | else: 276 | raise Exception("Unknown action: %s" % action) 277 | except: 278 | self.logger.error(traceback.format_exc()) 279 | 280 | def __on_error(self, error): 281 | '''Called on fatal websocket errors. We exit on these.''' 282 | if not self.exited: 283 | self.logger.error("Error : %s" % error) 284 | raise websocket.WebSocketException(error) 285 | 286 | def __on_open(self): 287 | '''Called when the WS opens.''' 288 | self.logger.debug("WebSocket Opened.") 289 | 290 | def __on_close(self): 291 | '''Called on websocket close.''' 292 | self.logger.info('WebSocket Closed') 293 | 294 | 295 | # Utility method for finding an item in the store. 296 | # When an update comes through on the websocket, we need to figure out which item in the array it is 297 | # in order to match that item. 298 | # 299 | # Helpfully, on a data push (or on an HTTP hit to /api/v1/schema), we have a "keys" array. These are the 300 | # fields we can use to uniquely identify an item. Sometimes there is more than one, so we iterate through all 301 | # provided keys. 302 | def find_by_keys(keys, table, matchData): 303 | for item in table: 304 | if all(item[k] == matchData[k] for k in keys): 305 | return item 306 | 307 | 308 | def order_leaves_quantity(o): 309 | if o['leavesQty'] is None: 310 | return True 311 | return o['leavesQty'] > 0 312 | -------------------------------------------------------------------------------- /pybitmex/bitmex.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from datetime import datetime, timezone 3 | from dateutil.parser import parse 4 | 5 | from pybitmex import ws, rest, models 6 | 7 | 8 | class BitMEXClient: 9 | 10 | def __init__( 11 | self, 12 | uri="https://testnet.bitmex.com/api/v1/", 13 | symbol="XBTUSD", 14 | api_key=None, 15 | api_secret=None, 16 | use_websocket=True, 17 | use_rest=True, 18 | subscriptions=None, 19 | order_id_prefix="", 20 | agent_name="trading_bot", 21 | http_timeout=7, 22 | expiration_seconds=3600, 23 | ws_refresh_interval_seconds=600 24 | ): 25 | self.logger = logging.getLogger(__name__) 26 | 27 | self.uri = uri 28 | self.symbol = symbol 29 | self.is_running = True 30 | if use_websocket: 31 | self.ws_client = ws.BitMEXWebSocketClient( 32 | endpoint=uri, 33 | symbol=symbol, 34 | api_key=api_key, 35 | api_secret=api_secret, 36 | subscriptions=subscriptions, 37 | expiration_seconds=expiration_seconds 38 | ) 39 | self.ws_refresh_interval_seconds = ws_refresh_interval_seconds 40 | else: 41 | self.ws_client = None 42 | 43 | if use_rest: 44 | self.rest_client = rest.RestClient( 45 | uri=uri, 46 | api_key=api_key, 47 | api_secret=api_secret, 48 | symbol=symbol, 49 | order_id_prefix=order_id_prefix, 50 | agent_name=agent_name, 51 | timeout=http_timeout, 52 | expiration_seconds=expiration_seconds 53 | ) 54 | else: 55 | self.rest_client = None 56 | self.order_id_prefix = order_id_prefix 57 | 58 | def close(self): 59 | self.is_running = False 60 | 61 | if self.ws_client: 62 | self.ws_client.exit() 63 | 64 | if self.rest_client: 65 | self.rest_client.close() 66 | 67 | def get_last_ws_update(self, table_name): 68 | return self.ws_client.updates.get(table_name) 69 | 70 | def _select_ws_client(self, table_name): 71 | return self.ws_client 72 | 73 | def ws_raw_instrument(self): 74 | return self._select_ws_client('instrument').get_instrument() 75 | 76 | def ws_market_state(self): 77 | instrument = self.ws_raw_instrument() 78 | return instrument["state"] 79 | 80 | def is_market_in_normal_state(self): 81 | state = self.ws_market_state() 82 | return state == "Open" or state == "Closed" 83 | 84 | def ws_raw_order_books_of_market(self): 85 | table_name = self.ws_client.get_order_book_table_name() 86 | return self._select_ws_client(table_name).market_depth() 87 | 88 | def ws_sorted_bids_and_asks_of_market(self): 89 | depth = self.ws_raw_order_books_of_market() 90 | bids = sorted([b for b in depth if b["side"] == "Buy"], key=lambda b: b["price"], reverse=True) 91 | asks = sorted([b for b in depth if b["side"] == "Sell"], key=lambda b: b["price"], reverse=False) 92 | 93 | def prune(order_books): 94 | return [{"price": float(each["price"]), "size": int(each["size"])} for each in order_books] 95 | 96 | return prune(bids), prune(asks) 97 | 98 | def ws_raw_recent_trades_of_market(self): 99 | return self._select_ws_client('trade').recent_trades() 100 | 101 | def ws_sorted_recent_trade_objects_of_market(self, reverse=False): 102 | raw_trades = self.ws_raw_recent_trades_of_market() 103 | result = [models.Trade(t["trdMatchID"], parse(t["timestamp"]).astimezone(timezone.utc), 104 | t["side"], float(t["price"]), int(t["size"])) for t in raw_trades] 105 | return sorted([t for t in result], key=lambda t: (t.timestamp, t.trd_match_id), reverse=reverse) 106 | 107 | def ws_raw_current_position(self): 108 | """ 109 | [{'account': XXXXX, 'symbol': 'XBTUSD', 'currency': 'XBt', 'underlying': 'XBT', 110 | 'quoteCurrency': 'USD', 'commission': 0.00075, 'initMarginReq': 0.01, 111 | 'maintMarginReq': 0.005, 'riskLimit': 20000000000, 'leverage': 100, 'crossMargin': True, 112 | 'deleveragePercentile': None, 'rebalancedPnl': 0, 'prevRealisedPnl': 0, 113 | 'prevUnrealisedPnl': 0, 'prevClosePrice': 3972.24, 114 | 'openingTimestamp': '2019-03-25T07:00:00.000Z', 'openingQty': 0, 'openingCost': 0, 'openingComm': 0, 115 | 'openOrderBuyQty': 0, 'openOrderBuyCost': 0, 'openOrderBuyPremium': 0, 'openOrderSellQty': 0, 116 | 'openOrderSellCost': 0, 'openOrderSellPremium': 0, 'execBuyQty': 0, 117 | 'execBuyCost':0, 'execSellQty': 30, 'execSellCost': 756060, 'execQty': -30, 'execCost': 756060, 118 | 'execComm': -189, 'currentTimestamp': '2019-03-25T07:27:06.107Z', 119 | 'currentQty': -30, 'currentCost': 756060, 'currentComm': -189, 'realisedCost': 0, 120 | 'unrealisedCost': 756060, 'grossOpenCost': 0, 'grossOpenPremium': 0, 121 | 'grossExecCost': 756060, 'isOpen': True, 'markPrice': 3964.82, 'markValue': 756660, 122 | 'riskValue': 756660, 'homeNotional': -0.0075666, 'foreignNotional': 30, 'posState': '', 123 | 'posCost': 756060, 'posCost2': 756060, 'posCross': 0, 'posInit': 7561, 'posComm': 573, 124 | 'posLoss': 0, 'posMargin': 8134, 'posMaint': 4712, 'posAllowance': 0, 125 | 'taxableMargin': 0, 'initMargin': 0, 'maintMargin': 8734, 'sessionMargin': 0, 126 | 'targetExcessMargin': 0, 'varMargin': 0, 'realisedGrossPnl': 0, 'realisedTax': 0, 127 | 'realisedPnl': 189, 'unrealisedGrossPnl': 600, 'longBankrupt': 0, 'shortBankrupt': 0, 128 | 'taxBase': 0, 'indicativeTaxRate': None, 'indicativeTax': 0, 'unrealisedTax': 0, 129 | 'unrealisedPnl': 600, 'unrealisedPnlPcnt': 0.0008, 'unrealisedRoePcnt': 0.0794, 130 | 'simpleQty': None, 'simpleCost': None, 'simpleValue': None, 'simplePnl': None, 131 | 'simplePnlPcnt': None, 'avgCostPrice': 3968, 'avgEntryPrice': 3968, 132 | 'breakEvenPrice':3968.5, 'marginCallPrice': 100000000, 'liquidationPrice': 100000000, 133 | 'bankruptPrice': 100000000, 'timestamp': '2019-03-25T07:27:06.107Z', 'lastPrice': 3964.82, 134 | 'lastValue': 756660}] 135 | """ 136 | return self._select_ws_client('position').positions() 137 | 138 | def ws_current_position_size(self): 139 | json_array = self.ws_raw_current_position() 140 | for each in json_array: 141 | if each["symbol"] == self.symbol: 142 | return int(each["currentQty"]) 143 | return 0 144 | 145 | def ws_raw_open_orders_of_account(self): 146 | return self._select_ws_client('order').open_orders(self.order_id_prefix) 147 | 148 | def ws_open_order_objects_of_account(self): 149 | """ 150 | [{'orderID': '57180f5f-d16a-62d6-ff8d-d1430637a8d9', 151 | 'clOrdID': '', 'clOrdLinkID': '', 152 | 'account': XXXXX, 'symbol': 'XBTUSD', 'side': 'Sell', 153 | 'simpleOrderQty': None, 154 | 'orderQty': 30, 'price': 3968, 155 | 'displayQty': None, 'stopPx': None, 'pegOffsetValue': None, 156 | 'pegPriceType': '', 'currency': 'USD', 'settlCurrency': 'XBt', 157 | 'ordType': 'Limit', 'timeInForce': 'GoodTillCancel', 158 | 'execInst': 'ParticipateDoNotInitiate', 'contingencyType': '', 159 | 'exDestination': 'XBME', 'ordStatus': 'New', 'triggered': '', 160 | 'workingIndicator': True, 'ordRejReason': '', 'simpleLeavesQty': None, 161 | 'leavesQty': 30, 'simpleCumQty': None, 'cumQty': 0, 'avgPx': None, 162 | 'multiLegReportingType': 'SingleSecurity', 'text': 'Submission from www.bitmex.com', 163 | 'transactTime': '2019-03-25T07:10:34.290Z', 'timestamp': '2019-03-25T07:10:34.290Z'}] 164 | """ 165 | # clOrdID, orderID, side, orderQty, price 166 | def order_obj_from_json(json): 167 | return models.OpenOrder( 168 | json["orderID"], json["clOrdID"], 169 | json["side"], json["orderQty"], json["price"], 170 | parse(json["timestamp"]).astimezone(timezone.utc) 171 | ) 172 | 173 | json_array = self.ws_raw_open_orders_of_account() 174 | bids = [order_obj_from_json(each) for each in json_array if each["side"] == "Buy"] 175 | asks = [order_obj_from_json(each) for each in json_array if each["side"] == "Sell"] 176 | return models.OpenOrders( 177 | bids=sorted(bids, key=lambda o: o.price, reverse=True), 178 | asks=sorted(asks, key=lambda o: o.price, reverse=False) 179 | ) 180 | 181 | def ws_recent_trades_of_account(self): 182 | """ 183 | [{'execID': '0e14ddd0-702d-7338-82d8-fd4c1a419d03', 184 | 'orderID': '57180f5f-d16a-62d6-ff8d-d1430637a8d9', 185 | 'clOrdID': '', 'clOrdLinkID': '', 'account': XXXXX, 186 | 'symbol':'XBTUSD', 'side': 'Sell', 'lastQty': 30, 'lastPx': 3968, 187 | 'underlyingLastPx': None, 'lastMkt': 'XBME', 'lastLiquidityInd': 'AddedLiquidity', 188 | 'simpleOrderQty': None, 'orderQty': 30, 'price': 3968, 189 | 'displayQty': None, 'stopPx': None, 'pegOffsetValue': None, 190 | 'pegPriceType': '', 'currency': 'USD', 'settlCurrency': 'XBt', 'execType': 'Trade', 191 | 'ordType': 'Limit', 'timeInForce': 'GoodTillCancel', 'execInst': 'ParticipateDoNotInitiate', 192 | 'contingencyType': '', 'exDestination': 'XBME', 193 | 'ordStatus': 'Filled', 'triggered': '', 'workingIndicator': False, 194 | 'ordRejReason': '', 'simpleLeavesQty': None, 'leavesQty': 0, 'simpleCumQty': None, 'cumQty':30, 195 | 'avgPx': 3968, 'commission': -0.00025, 'tradePublishIndicator': 'PublishTrade', 196 | 'multiLegReportingType': 'SingleSecurity', 'text': 'Submission from www.bitmex.com', 197 | 'trdMatchID': '34137715-0068-a923-4685-6dbc70e6d2ac', 'execCost': 756060, 198 | 'execComm': -189, 'homeNotional': -0.0075606, 'foreignNotional': 30, 199 | 'transactTime': '2019-03-25T07:26:06.334Z', 'timestamp': '2019-03-25T07:26:06.334Z'}] 200 | """ 201 | return self._select_ws_client('execution').executions() 202 | 203 | def ws_raw_balances_of_account(self): 204 | return self._select_ws_client('margin').funds() 205 | 206 | def ws_balances_of_account_object(self): 207 | """ 208 | {'account': XXXXX, 'currency': 'XBt', 'riskLimit': 1000000000000, 'prevState': '', 209 | 'state': '', 'action': '', 'amount': 377084143, 'pendingCredit': 0, 'pendingDebit': 0, 210 | 'confirmedDebit': 0, 'prevRealisedPnl': 1038, 'prevUnrealisedPnl': 0, 'grossComm': -567, 211 | 'grossOpenCost': 0, 'grossOpenPremium': 0, 'grossExecCost': 756345, 'grossMarkValue': 756090, 212 | 'riskValue': 756090, 'taxableMargin': 0, 'initMargin': 0, 'maintMargin': 8142, 213 | 'sessionMargin': 0, 'targetExcessMargin': 0, 'varMargin': 0, 'realisedPnl': 1227, 214 | 'unrealisedPnl': -540, 'indicativeTax': 0, 'unrealisedProfit': 0, 'syntheticMargin': None, 215 | 'walletBalance': 377085370, 'marginBalance': 377084830, 'marginBalancePcnt': 1, 216 | 'marginLeverage': 0.0020050925941518254, 'marginUsedPcnt': 0, 'excessMargin': 377076688, 217 | 'excessMarginPcnt': 1, 'availableMargin': 377076688, 'withdrawableMargin': 377076688, 218 | 'timestamp': '2019-03-25T07:56:25.462Z', 'grossLastValue': 756090, 'commission': None} 219 | """ 220 | satoshis_for_btc = 100000000 221 | data = self.ws_raw_balances_of_account() 222 | withdrawable_balance = float(data['withdrawableMargin']) / satoshis_for_btc 223 | wallet_balance = float(data['walletBalance']) / satoshis_for_btc 224 | return withdrawable_balance, wallet_balance 225 | 226 | def rest_place_orders(self, new_order_list, post_only=True, max_retries=None): 227 | if len(new_order_list) == 0: 228 | return 229 | self.rest_client.place_orders([o for o in new_order_list], post_only=post_only, max_retries=max_retries) 230 | 231 | def rest_market_close_position(self, order, max_retries=None): 232 | self.rest_client.market_close_position(order, max_retries=max_retries) 233 | 234 | def rest_cancel_orders(self, order_id_list, max_retries=None): 235 | if len(order_id_list) == 0: 236 | return 237 | self.rest_client.cancel_orders(order_id_list, max_retries=max_retries) 238 | 239 | def rest_cancel_all_orders(self): 240 | open_orders = self.ws_open_order_objects_of_account() 241 | self.rest_cancel_orders([o.order_id for o in open_orders.to_list()]) 242 | 243 | def rest_get_raw_orders_of_account(self, filter_json_obj, count=500): 244 | return self.rest_client.get_orders_of_account(filter_json_obj, count) 245 | 246 | def rest_get_raw_positions_of_account(self, filter_json_obj, count=500): 247 | return self.rest_client.get_positions_of_account(filter_json_obj, count) 248 | 249 | def rest_get_raw_trade_history_of_account(self, filter_json_obj, count=500): 250 | trades = self.rest_client.get_trade_history(filter_json_obj, count) 251 | return [t for t in trades if t['symbol'] == self.symbol and t['execType'] == 'Trade'] 252 | 253 | def rest_get_raw_margin_of_account(self): 254 | return self.rest_client.get_user_margin() 255 | 256 | @staticmethod 257 | def create_daily_filter(year, month, day): 258 | return {"timestamp.date": "{:04}-{:02}-{:02}".format(year, month, day)} 259 | 260 | @staticmethod 261 | def create_hourly_filter(year, month, day, hour): 262 | result = BitMEXClient.create_daily_filter(year, month, day) 263 | result['timestamp.hh'] = "{:02}".format(hour) 264 | return result 265 | 266 | @staticmethod 267 | def create_minutely_filter(year, month, day, hour, minute): 268 | result = BitMEXClient.create_daily_filter(year, month, day) 269 | result['timestamp.hh'] = "{:02}".format(hour) 270 | result['timestamp.uu'] = "{:02}".format(minute) 271 | return result 272 | 273 | @staticmethod 274 | def create_time_range_filter(start_dt: datetime, end_dt: datetime): 275 | result = {} 276 | if start_dt: 277 | result['startTime'] = start_dt.strftime("%Y-%m-%d %H:%M:%S") 278 | if end_dt: 279 | result['endTime'] = end_dt.strftime("%Y-%m-%d %H:%M:%S") 280 | return result 281 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------