Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // --------------------------------------------------------------------------------------------------------------------
- // DERIBOT - 0.3
- // --------------------------------------------------------------------------------------------------------------------
- // Author: FrostyAF from the Krown's Crypto Cave discord group
- // Version: 0.3
- // Dedication: Dedicated to @christiaan's mom, what a classy lady!
- // Disclaimer: Use this bot at your own risk, I accept no responsibility if you get rekt
- // Usage: This bot is intended to be used with TradingView webhooks or via cli commands. Ensure that you have a
- // PHP web server running and that you have cloned CCXT into the bot directory using:
- // git clone https://github.com/ccxt/ccxt.git
- // Ensure the web server is publicly accessible, and then configure your Trading View alerts to call the
- // webhook using the appropriate commands:
- // Webhook Example URLs:
- // https://my.bot.com/webhooks/?command=LONGENTRY (will use the default ORDER_SIZE configured below)
- // https://my.bot.com/webhooks/?command=LONGEXIT (Will exit the full current long position)
- // https://my.bot.com/webhooks/?command=SHORTENTRY&size=20000 (Custom order size in request)
- // https://my.bot.com/webhooks/?command=LONGEXIT (Will exit the full current short position)
- // CLI Examples:
- // php bot.php LONGENTRY (Will use the default ORDER_SIZE specified below)
- // php bot.php LONGENTRY 10000 (Will enter long position of USD 10000)
- // php bot.php LONGEXIT (Will exit the full current long position)
- // php bot.php SHORTENTRY 20000 (Will enter short position of USD 20000)
- // php bot.php SHORTEXIT (Will exit the full current short position)
- // php bot.php BALANCE (Current account balances)
- // php bot.php TRADES (Recent trades, oldest listed first)
- // php bot.php POSITION (Show current open position, if any)
- // Changelog: 0.1 : Initial version
- // 0.2 : Code cleanup
- // Removed the FLIPLONG and FLIPSHORT commands. Incorporated into LONGENTRY and SHORTENTRY.
- // Added POSITION command to show current position
- // Added size parameter
- // 0.3 : Added ORDERS and CANCEL command to show open orders and cancel orders (limit orders)
- // Added price parameter (limit orders)
- // Changed output of BALANCE, TRADES and POSITION commands to JSON
- // Changed IP whitelist to const to prevent skullfuckery
- // --------------------------------------------------------------------------------------------------------------------
- // https://ccxt.readthedocs.io/en/latest/README.html
- include('ccxt/ccxt.php');
- // Script settings
- const EXCHANGE = 'deribit'; // Any exchange supported by CCXT
- const API_KEY = 'Enter API key here'; // API key
- const API_SECRET = 'Enter secret here'; // API secret
- const MARKET = 'BTC-PERPETUAL'; // Market to trade
- const ORDER_SIZE = 100; // Default Order size in USD (if not specified in GET)
- const CONTRACT_SIZE = 10; // Deribit is $10 per contract
- const LOG_FILE = 'deribot.log'; // Log file
- const WHITELIST = [ // GET request whitelist addresses (from TradingView)
- '52.89.214.238',
- '34.212.75.30',
- '54.218.53.128',
- '52.32.178.7'
- ];
- // Function to log messages to a log file
- function logger($message) {
- file_put_contents(LOG_FILE, date('Y-m-d H:i:s').' : '.$message.PHP_EOL, FILE_APPEND);
- echo date('Y-m-d H:i:s').' : '.$message.PHP_EOL;
- }
- // Check that request is coming from an authorised Trading View IP
- if (isset($_GET['command'])) {
- if (!in_array($_SERVER['REMOTE_ADDR'], WHITELIST)) {
- logger('Request received from invalid address');
- die;
- }
- }
- // Connect to Exchange
- $exchange_id = EXCHANGE;
- $exchange_class = "\\ccxt\\$exchange_id";
- $exchange = new $exchange_class (array (
- 'apiKey' => API_KEY,
- 'secret' => API_SECRET,
- ));
- // Get balance and market data
- $ticker = $exchange->fetch_ticker(MARKET);
- $balance = $exchange->fetch_balance();
- $btcbalance = (round($balance['BTC']['total'] * 10000) / 10000);
- // Get current position in market
- $positions = $exchange->private_get_positions();
- $position = false;
- $isLong = false;
- $isShort = false;
- foreach($positions['result'] as $positionRaw) {
- if ($positionRaw['instrument']=MARKET) {
- $position = $positionRaw;
- }
- }
- $isLong = (is_array($position) ? ($position['direction'] == 'buy') : false);
- $isShort = (is_array($position) ? ($position['direction'] == 'sell') : false);
- // Get bot commands and parameters from GET request or CLI
- $command = isset($_GET['command']) ? $_GET['command'] : $argv[1];
- $size = isset($_GET['size']) ? $_GET['size'] : ( isset($argv[2]) ? $argv[2] : ORDER_SIZE);
- $orderSize = $size / CONTRACT_SIZE;
- $price = isset($_GET['price']) ? $_GET['price'] : ( isset($argv[3]) ? $argv[3] : null);
- // Execute appropriate bot command on Exchange
- $order = false;
- switch(strtoupper($command)) {
- case 'LONGENTRY' : $order = ($isShort && !$price) ? abs($position['size']) + $orderSize : $orderSize;
- break;
- case 'LONGEXIT' : $order = $isLong ? 0 - $position['size'] : 0;
- break;
- case 'SHORTENTRY' : $order = 0 - (($isLong && !$price) ? $position['size'] + $orderSize : $orderSize);
- break;
- case 'SHORTEXIT' : $order = $isShort ? abs($position['size']) : 0;
- break;
- case 'BALANCE' : echo json_encode((object) $balance, JSON_PRETTY_PRINT).PHP_EOL;
- break;
- case 'TRADES' : $trades = $exchange->fetch_my_trades(MARKET);
- echo json_encode((object) $trades, JSON_PRETTY_PRINT).PHP_EOL;
- break;
- case 'ORDERS' : $orders = $exchange->fetch_open_orders(MARKET);
- echo json_encode((object) $orders, JSON_PRETTY_PRINT).PHP_EOL;
- break;
- case 'CANCEL' : $orders = $exchange->fetch_open_orders(MARKET);
- foreach ($orders as $item)
- $exchange->cancel_order($item['id']);
- echo json_encode((object) $orders, JSON_PRETTY_PRINT).PHP_EOL;
- break;
- case 'POSITION' : echo json_encode((object) $position, JSON_PRETTY_PRINT).PHP_EOL;
- break;
- }
- if ($order) {
- $type = ((strtoupper($price) !== 'MARKET') && (is_numeric($price))) ? 'limit' : 'market';
- $dir = $order > 0 ? 'buy' : ($order < 0 ? 'sell' : null);
- $result = $exchange->create_order(MARKET, $type, $dir, abs($order), $price);
- if ($result) {
- echo json_encode((object) $result, JSON_PRETTY_PRINT).PHP_EOL;
- logger('TRADE: USD '.str_pad(($order) * CONTRACT_SIZE, 5, " ", STR_PAD_LEFT).', BALANCE: BTC '.$btcbalance);
- } else {
- logger('FAILED TO EXECUTE TRADE!!!');
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement