Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 8.26 KB | None | 0 0
  1. <?php
  2.  
  3.     // --------------------------------------------------------------------------------------------------------------------
  4.     //  DERIBOT - 0.3
  5.     // --------------------------------------------------------------------------------------------------------------------
  6.     //  Author:     FrostyAF from the Krown's Crypto Cave discord group
  7.     //  Version:    0.3
  8.     //  Dedication: Dedicated to @christiaan's mom, what a classy lady!
  9.     //  Disclaimer: Use this bot at your own risk, I accept no responsibility if you get rekt
  10.     //  Usage:      This bot is intended to be used with TradingView webhooks or via cli commands. Ensure that you have a
  11.     //              PHP web server running and that you have cloned CCXT into the bot directory using:
  12.     //                  git clone https://github.com/ccxt/ccxt.git
  13.     //              Ensure the web server is publicly accessible, and then configure your Trading View alerts to call the
  14.     //              webhook using the appropriate commands:
  15.     //              Webhook Example URLs:
  16.     //                  https://my.bot.com/webhooks/?command=LONGENTRY (will use the default ORDER_SIZE configured below)
  17.     //                  https://my.bot.com/webhooks/?command=LONGEXIT  (Will exit the full current long position)
  18.     //                  https://my.bot.com/webhooks/?command=SHORTENTRY&size=20000  (Custom order size in request)
  19.     //                  https://my.bot.com/webhooks/?command=LONGEXIT  (Will exit the full current short position)
  20.     //              CLI Examples:
  21.     //                  php bot.php LONGENTRY           (Will use the default ORDER_SIZE specified below)
  22.     //                  php bot.php LONGENTRY  10000    (Will enter long position of USD 10000)
  23.     //                  php bot.php LONGEXIT            (Will exit the full current long position)
  24.     //                  php bot.php SHORTENTRY 20000    (Will enter short position of USD 20000)
  25.     //                  php bot.php SHORTEXIT           (Will exit the full current short position)
  26.     //                  php bot.php BALANCE             (Current account balances)
  27.     //                  php bot.php TRADES              (Recent trades, oldest listed first)
  28.     //                  php bot.php POSITION            (Show current open position, if any)
  29.     //  Changelog:  0.1 : Initial version
  30.     //              0.2 : Code cleanup
  31.     //                    Removed the FLIPLONG and FLIPSHORT commands. Incorporated into LONGENTRY and SHORTENTRY.
  32.     //                    Added POSITION command to show current position
  33.     //                    Added size parameter
  34.     //              0.3 : Added ORDERS and CANCEL command to show open orders and cancel orders (limit orders)
  35.     //                    Added price parameter (limit orders)
  36.     //                    Changed output of BALANCE, TRADES and POSITION commands to JSON
  37.     //                    Changed IP whitelist to const to prevent skullfuckery
  38.     // --------------------------------------------------------------------------------------------------------------------
  39.    
  40.     // https://ccxt.readthedocs.io/en/latest/README.html
  41.     include('ccxt/ccxt.php');
  42.  
  43.     // Script settings
  44.     const EXCHANGE      = 'deribit';                                      // Any exchange supported by CCXT
  45.     const API_KEY       = 'Enter API key here';                           // API key
  46.     const API_SECRET    = 'Enter secret here';                            // API secret
  47.     const MARKET        = 'BTC-PERPETUAL';                                // Market to trade
  48.     const ORDER_SIZE    = 100;                                            // Default Order size in USD (if not specified in GET)
  49.     const CONTRACT_SIZE = 10;                                             // Deribit is $10 per contract
  50.     const LOG_FILE      = 'deribot.log';                                  // Log file
  51.     const WHITELIST     = [                                               // GET request whitelist addresses (from TradingView)
  52.                                 '52.89.214.238',
  53.                                 '34.212.75.30',
  54.                                 '54.218.53.128',
  55.                                 '52.32.178.7'
  56.                           ];
  57.  
  58.     // Function to log messages to a log file
  59.     function logger($message) {
  60.         file_put_contents(LOG_FILE, date('Y-m-d H:i:s').' : '.$message.PHP_EOL, FILE_APPEND);
  61.         echo date('Y-m-d H:i:s').' : '.$message.PHP_EOL;
  62.     }
  63.  
  64.     // Check that request is coming from an authorised Trading View IP
  65.     if (isset($_GET['command'])) {
  66.         if (!in_array($_SERVER['REMOTE_ADDR'], WHITELIST)) {
  67.             logger('Request received from invalid address');
  68.             die;
  69.         }
  70.     }
  71.  
  72.     // Connect to Exchange
  73.     $exchange_id = EXCHANGE;
  74.     $exchange_class = "\\ccxt\\$exchange_id";
  75.     $exchange = new $exchange_class (array (
  76.                 'apiKey' => API_KEY,
  77.                 'secret' => API_SECRET,
  78.     ));
  79.  
  80.     // Get balance and market data
  81.     $ticker = $exchange->fetch_ticker(MARKET);
  82.     $balance = $exchange->fetch_balance();
  83.     $btcbalance = (round($balance['BTC']['total'] * 10000) / 10000);
  84.  
  85.     // Get current position in market
  86.     $positions = $exchange->private_get_positions();
  87.     $position = false;
  88.     $isLong = false;
  89.     $isShort = false;
  90.     foreach($positions['result'] as $positionRaw) {
  91.         if ($positionRaw['instrument']=MARKET) {
  92.             $position = $positionRaw;
  93.         }
  94.     }
  95.     $isLong  = (is_array($position) ? ($position['direction'] == 'buy') : false);
  96.     $isShort = (is_array($position) ? ($position['direction'] == 'sell') : false);
  97.  
  98.     // Get bot commands and parameters from GET request or CLI
  99.     $command = isset($_GET['command']) ? $_GET['command'] : $argv[1];
  100.     $size = isset($_GET['size']) ? $_GET['size'] : ( isset($argv[2]) ? $argv[2] : ORDER_SIZE);
  101.     $orderSize = $size / CONTRACT_SIZE;  
  102.     $price = isset($_GET['price']) ? $_GET['price'] : ( isset($argv[3]) ? $argv[3] : null);
  103.  
  104.     // Execute appropriate bot command on Exchange
  105.    
  106.     $order   = false;
  107.    
  108.     switch(strtoupper($command)) {
  109.         case 'LONGENTRY'    :   $order = ($isShort && !$price) ? abs($position['size']) + $orderSize : $orderSize;
  110.                                 break;
  111.         case 'LONGEXIT'     :   $order = $isLong ? 0 - $position['size'] : 0;
  112.                                 break;
  113.         case 'SHORTENTRY'   :   $order = 0 - (($isLong && !$price) ? $position['size'] + $orderSize : $orderSize);
  114.                                 break;
  115.         case 'SHORTEXIT'    :   $order = $isShort ? abs($position['size']) : 0;
  116.                                 break;
  117.         case 'BALANCE'      :   echo json_encode((object) $balance, JSON_PRETTY_PRINT).PHP_EOL;
  118.                                 break;
  119.         case 'TRADES'       :   $trades = $exchange->fetch_my_trades(MARKET);
  120.                                 echo json_encode((object) $trades, JSON_PRETTY_PRINT).PHP_EOL;
  121.                                 break;
  122.         case 'ORDERS'       :   $orders = $exchange->fetch_open_orders(MARKET);
  123.                                 echo json_encode((object) $orders, JSON_PRETTY_PRINT).PHP_EOL;
  124.                                 break;
  125.         case 'CANCEL'       :   $orders = $exchange->fetch_open_orders(MARKET);
  126.                                 foreach ($orders as $item)
  127.                                     $exchange->cancel_order($item['id']);
  128.                                 echo json_encode((object) $orders, JSON_PRETTY_PRINT).PHP_EOL;
  129.                                 break;
  130.         case 'POSITION'     :   echo json_encode((object) $position, JSON_PRETTY_PRINT).PHP_EOL;
  131.                                 break;
  132.     }
  133.  
  134.     if ($order) {
  135.  
  136.         $type = ((strtoupper($price) !== 'MARKET') && (is_numeric($price))) ? 'limit' : 'market';
  137.         $dir  = $order > 0 ? 'buy' : ($order < 0 ? 'sell' : null);
  138.         $result = $exchange->create_order(MARKET, $type, $dir, abs($order), $price);
  139.  
  140.         if ($result) {
  141.             echo json_encode((object) $result, JSON_PRETTY_PRINT).PHP_EOL;
  142.             logger('TRADE: USD '.str_pad(($order) * CONTRACT_SIZE, 5, " ", STR_PAD_LEFT).', BALANCE: BTC '.$btcbalance);
  143.         } else {
  144.             logger('FAILED TO EXECUTE TRADE!!!');
  145.         }    
  146.     }
  147.  
  148. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement